Sub topic 4
Handling errors with catchError
This chapter assumes you can write an Angular service that calls HttpClient, and that you know what an Observable is and how pipe() chains operators. Earlier chapters covered HttpErrorResponse and the difference between network, 4xx and 5xx failures. Here you will use that knowledge inside the RxJS catchError operator.
What catchError does
An HttpClient request is an Observable that either emits one response and completes, or fails with an HttpErrorResponse. When it fails, the error travels down the pipe and skips every operator that handles normal values, such as map. If nothing handles the error, it reaches the subscriber's error callback. If the subscriber has none, RxJS reports it as an unhandled error.
catchError intercepts that error notification. You give it a function that receives the error and must return an Observable. The stream then continues with that Observable instead of failing.
catchError((error: HttpErrorResponse, caught: Observable<User>) => /* an Observable */)The second argument, caught, is the source Observable. Returning it resubscribes, which means retrying. That is rarely what you want, because it retries forever with no delay. Use the retry operator for that, which a later chapter covers.
The three things a handler can return
Whatever you return decides what callers see. Returning something that is not an Observable is a type error in TypeScript. In plain JavaScript it fails at runtime.
| You return | Effect on subscribers | Typical use |
|---|---|---|
| `throwError(() => new Error(...))` | The stream fails with your error | Translate a low-level error into one your app understands |
| `of(fallback)` | The stream emits `fallback`, then completes | Optional data where a default is acceptable |
| `EMPTY` | The stream completes with no value | You already reported the problem and want the stream to end quietly |
Note that throwError takes a factory function, () => error. The older form throwError(error) is deprecated.
Translating errors in a service
The most common pattern puts catchError in the service method, so components never deal with HttpErrorResponse directly.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, catchError, throwError } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
return throwError(() => new Error('Network error. Check your connection.'));
}
return throwError(() => new Error(`Server returned ${error.status}`));
})
);
}
}Status 0 means the browser never received an HTTP response. The cause could be a dropped connection, a CORS failure, or a request that was cancelled. Every other status means the server answered, and you can inspect error.status and error.error (the parsed response body) for detail.
The caller now sees a plain Error with a message it can show. This hides the HTTP details, which is good for most components. The cost is that the original status code is gone. If callers need to branch on it, for example to treat 404 differently from 500, do not flatten everything to a string. Throw a custom error class that carries the status, or attach the original error as a cause.
import { HttpErrorResponse } from '@angular/common/http';
export class ApiError extends Error {
constructor(
message: string,
readonly status: number,
readonly original: HttpErrorResponse
) {
super(message);
this.name = 'ApiError';
}
}A handler can then call throwError(() => new ApiError('User not found', error.status, error)), and a component can check err instanceof ApiError && err.status === 404.
Providing a fallback value
Some failures should not break the page. A "featured products" strip that cannot load is better shown empty than as a full-page error. For that, return of(fallback).
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, catchError, of } from 'rxjs';
export interface Product {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class ProductService {
private http = inject(HttpClient);
getFeatured(): Observable<Product[]> {
return this.http.get<Product[]>('/api/products/featured').pipe(
catchError(() => of([]))
);
}
}Where to place catchError in the pipe
Operators run in order, so position matters.
- Put
catchErroraftermapif you want it to also catch exceptions thrown insidemap, such as a failed data transformation. - Put
catchErrorbeforemapif you want the handler's fallback value to pass through the transformation. - Put
catchErrorafterretryso that it only sees the error once retries are exhausted. If you put it beforeretry, the error is converted first andretrynever sees a failure to react to.
The last rule is the most common mistake when combining the two operators. The next chapters build on it.
Keeping an outer stream alive
A stream that fails is finished. This matters when HttpClient sits inside a longer-lived stream, such as a search box. If the error reaches the outer pipe, the whole search stops working until someone resubscribes.
The fix is to handle the error on the inner request, inside switchMap, so only that one request fails.
import { HttpClient } from '@angular/common/http';
import { Subject, catchError, of, switchMap } from 'rxjs';
export function createSearch(http: HttpClient) {
const terms = new Subject<string>();
const results$ = terms.pipe(
switchMap(term =>
http.get<string[]>('/api/search', { params: { q: term } }).pipe(
catchError(() => of([] as string[]))
)
)
);
return { terms, results$ };
}If catchError were placed after switchMap instead, one failed search would end results$, and later calls to terms.next(...) would produce nothing.
Common errors
- Returning a value instead of an Observable.
catchError(() => [])does not compile as intended. Wrap the value:catchError(() => of([])). - Swallowing errors silently. An empty handler such as
catchError(() => EMPTY)makes failures invisible. Log or report before you swallow. - Handling the same error twice. If the service converts the error and the component also has an
errorcallback, make sure each layer does one job: the service translates, the component displays. - Treating
error.erroras always an object. For a network failure it is aProgressEvent. For a server response it can be a string, parsed JSON, ornull. Check the type before reading fields from it. - Using
catchErrorto retry. Returningcaughtresubscribes immediately and without a limit. Useretrywith a count and delay instead.
Summary
catchError receives the failure and returns an Observable that replaces the failed stream. Throw a new error to translate it, emit a fallback to hide it, or complete with EMPTY to end quietly. Place it after retry, and place it inside switchMap when the outer stream must keep running.
Exercise
A search box uses terms$.pipe(switchMap(t => http.get<string[]>('/api/search?q=' + t)), catchError(() => of([] as string[]))). After one request returns a 500, typing more characters never updates the results. Why, and how do you fix it?
Show answer
The catchError is on the outer pipe. When the inner request fails, catchError replaces the whole stream with of([]), which emits once and completes, so terms$ is no longer subscribed. Move catchError inside switchMap, on the http.get pipe, so only that single request is replaced by the fallback and the outer stream keeps listening.
Exercise
You want UserService.getUser to let components show a specific message for 404 but a generic one for everything else. Which two things should the catchError handler do, and what should it return?
Show answer
Inspect error.status and build an error that preserves it, for example a custom ApiError with a message and the status code. It should return throwError(() => apiError). The component can then check err.status === 404 and choose its message.