Sub topic 1
HttpClient requests and where they can fail
Before you write error handling, you need to know where in a request's life a failure can happen and how Angular reports it. This chapter maps those failure points and shows how they reach your code. Later chapters cover how to inspect, handle and retry them.
Prerequisites
This chapter assumes you already know:
- TypeScript fundamentals, including interfaces and generics.
- How to write a basic Angular component and an injectable service.
- What an RxJS
Observableis, and howsubscribe()andpipe()work. - How to make a simple
HttpClientrequest such ashttp.get<T>(url).
The examples use standalone APIs (provideHttpClient, inject), which current Angular versions use by default.
An HttpClient request is a cold Observable
HttpClient methods such as get, post and put return an Observable. The call itself sends nothing. The request goes out when something subscribes.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Product {
id: number;
title: string;
}
@Injectable({ providedIn: 'root' })
export class ProductService {
private http = inject(HttpClient);
getProduct(id: number): Observable<Product> {
// No request is sent here. This only builds the Observable.
return this.http.get<Product>(`/api/products/${id}`);
}
}Three consequences follow from this, and each one affects error handling:
- No subscription means no request and no error. If a method calls
http.post(...)and nobody subscribes, the server never sees it. - Each subscription sends its own request. Two
subscribe()calls on the same Observable produce two HTTP calls. Theasyncpipe used twice on the same Observable does the same. Without caching or sharing, one failing endpoint can report the same failure more than once. - Unsubscribing cancels the request. If the component is destroyed or a
switchMapreplaces the request,HttpClientaborts the in-flight call. A cancelled request is not an error. The Observable emits nothing and your error callback does not run.
The two outcomes of a request
An Observable can finish in one of two terminal ways: complete or error. For a normal HTTP request, the Observable emits one value (the response body) and then completes. If the request fails, it emits an error notification instead and ends. It does not emit a value and does not complete.
import { Component, inject, OnInit } from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector: 'app-product',
standalone: true,
template: `<p>{{ status }}</p>`,
})
export class ProductComponent implements OnInit {
private products = inject(ProductService);
status = 'loading';
ngOnInit(): void {
this.products.getProduct(7).subscribe({
next: (product) => (this.status = `Loaded ${product.title}`),
error: (err) => (this.status = 'Failed'),
complete: () => console.log('request finished successfully'),
});
}
}The error callback is the only place a failure shows up. If you pass only a next function, a failed request surfaces in the console as an unhandled error. The rest of this tutorial is about deciding what to do in that error channel, or before it reaches your subscriber.
For the error callback to run, the failure must come through the Observable. The next sections list what counts as a failure.
Where a request can fail
A request passes through several stages. Each stage fails differently.
Failures before the request is sent
Interceptors run before the request reaches the network. An interceptor can throw, or return an Observable that errors. For example, a token lookup might fail. In that case the request is never sent, and the failure still arrives on the error channel. An error that does not come from the server can therefore still appear in your error callback.
Network failures
The browser can fail to complete the exchange at all. Typical causes are:
- The device is offline.
- DNS lookup fails.
- The server refuses the connection or is down.
- A CORS check blocks the response.
- The connection drops mid-request.
In these cases there is no HTTP response and no status code to read. HttpClient reports the failure as an HttpErrorResponse whose status is 0. The next chapter looks at this object in detail.
Error status codes
If the server answers with a status outside the 2xx range, HttpClient treats the request as failed. This differs from the browser fetch API, which resolves normally on a 404 or 500. With HttpClient, a 404 or a 500 goes to the error channel, and your next callback never runs.
Redirects (3xx) are followed by the browser before Angular sees a response, so you rarely handle them yourself.
Parse failures on a successful status
A response can have status 200 and still produce an error. By default HttpClient expects a JSON body. If the server returns HTML, such as a login page or a proxy error page, with status 200, the JSON parse fails. The Observable then errors with an HttpErrorResponse that carries the 200 status and the parse error. A 200 status therefore does not guarantee that next will run.
The responseType option controls how the body is read. With responseType: 'text' no JSON parsing happens, so this failure cannot occur.
Timeouts
HttpClient has no built-in timeout. A request with no response and no network error can wait until the browser gives up, which can take minutes. If you want a time limit, you add one yourself with an RxJS operator. A later chapter shows how.
Errors in your own code
An exception thrown inside your next callback is not an HTTP failure. It is a bug in your code. HttpClient does not route it to your error callback. Keep this in mind when you read stack traces: an error that appears while handling a successful response was not caused by the request.
Seeing more than the body
By default you get only the parsed body. To inspect the status and headers of a successful response, use observe: 'response'.
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface Order {
id: number;
total: number;
}
@Injectable({ providedIn: 'root' })
export class OrderService {
private http = inject(HttpClient);
createOrder(order: Order): Observable<HttpResponse<Order>> {
return this.http.post<Order>('/api/orders', order, { observe: 'response' });
}
}With this option, next receives an HttpResponse<Order>. You can read response.status and response.headers, and response.body holds the parsed data. Failures still go to the error channel, as before. The option only changes what a success looks like.
Registering HttpClient
None of the examples above work unless HttpClient is provided. In a standalone application, register it once in the application config:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideHttpClient()],
};Forgetting this produces a NullInjectorError for HttpClient when the service is created. That is a configuration error and it appears at startup. It is not a request failure.
A quick reference
| Failure point | What happens | Reaches `error` callback? |
|---|---|---|
| Interceptor throws | Request is never sent | Yes |
| No network, DNS or CORS failure | No response, `status` is `0` | Yes |
| 4xx or 5xx status | Server responded with a failure | Yes |
| 2xx status, body does not parse | Response is unusable | Yes |
| No response and no network error | Request waits, no built-in limit | No, until you add a timeout |
| Unsubscribe | Request is aborted | No |
| Exception in your `next` callback | Bug in your code | No |
What to take into the next chapter
- A request is lazy. It runs per subscription, and it ends in either
completeorerror. - Network failures, error statuses, parse failures and interceptor errors all arrive on the same error channel.
- That one channel carries different kinds of failure, so your handling code must tell them apart before choosing a response. Reading
HttpErrorResponseis how you do that.
Exercise
A service method calls this.http.delete('/api/items/5') and returns nothing. A component calls the method, but the server never receives a DELETE request and no error appears. What is the cause, and how do you fix it?
Show answer
The method builds a cold Observable but nothing subscribes to it, so no request is sent. Return the Observable from the service and subscribe in the caller (or subscribe inside the service). Each subscription then sends one request.
Exercise
An endpoint returns status 200 with an HTML login page instead of JSON. The next callback never runs and the error callback fires. Why does this happen, and which HttpClient option would avoid the parse step?
Show answer
By default HttpClient parses the body as JSON. The HTML cannot be parsed, so the Observable errors with an HttpErrorResponse that still carries status 200. Setting responseType: 'text' skips JSON parsing, though you would then need to detect the unexpected HTML yourself.
Exercise
A component subscribes to the same http.get Observable twice, once in the template through the async pipe and once in ngOnInit. How many requests are sent, and how many error notifications can occur if the server is down?
Show answer
Two requests are sent, because each subscription triggers its own request. If the server is down, each one fails separately, so two error notifications can occur.