Sub topic 4
Handling errors with catchError
This chapter assumes you know TypeScript, Angular services, and RxJS pipe(). You should also have made requests with HttpClient and seen what an HttpErrorResponse contains. Here you will use catchError to turn a failed request into something your callers can use.
What catchError does
catchError is an RxJS operator that you place inside pipe(). It runs only when the source Observable signals an error. Values pass through it untouched.
The function you give it receives the error and must return an Observable. That Observable replaces the failed one. You have three common choices:
throwError(() => new Error(...))rethrows a clearer error.of(fallback)recovers by emitting a substitute value, then completes.EMPTYcompletes without emitting anything.
Mapping an error in a service
A service is a good place to translate low-level failures into messages. This method treats status 0 as a network failure and anything else as a server response.
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}`));
})
);
}
}Callers now receive a plain Error with a readable message. They no longer need to know about HttpErrorResponse. The return type stays Observable<User>, because throwError produces an Observable that never emits a value.
Recovering with a fallback
Some failures should not reach the user. A list of suggestions can safely be empty if the request fails. Here catchError returns of([]).
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, catchError, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SuggestionService {
private http = inject(HttpClient);
getSuggestions(): Observable<string[]> {
return this.http.get<string[]>('/api/suggestions').pipe(
catchError(() => of([]))
);
}
}Common mistakes
- Returning a value instead of an Observable.
catchError(() => [])fails at runtime, because RxJS expects an Observable. Wrap it:of([]). - Throwing a string.
throwError(() => 'failed')loses the stack trace. Throw anError. - Discarding the original error. The mapped message drops details such as
error.urland the response body. If you need them for logging, log inside the handler before you rethrow. - Wrong operator order.
catchErrorends the stream with its replacement. If you addretrylater, put it beforecatchErrorin the pipe. Otherwise the retry never sees the error. - Catching too early. If every service swallows errors, a global handler or interceptor never sees them. Handle an error where you can do something useful with it, and rethrow otherwise.
Exercise
A method returns this.http.get<string[]>('/api/tags').pipe(catchError(() => [])). Why does this break when the request fails, and how do you fix it so the caller receives an empty array?
Show answer
catchError must return an Observable, and [] is a plain array. Return of([]) instead: catchError(() => of([])). The subscriber then receives an empty array and the stream completes normally.