Sub topic 7
Handling Errors with catchError and retry
This chapter assumes you already know pipe, basic operators such as map, and how HttpClient returns an observable for each request. It explains what happens when a stream fails and how to recover with catchError and retry.
An Error Ends the Stream
An observable can send an error notification only once. After it does, the stream is finished. It will not emit more values or a complete signal, and every operator downstream stops working. For an HTTP request, this means a 500 response or a network failure reaches your error callback. If you have no error callback, RxJS rethrows the error as an unhandled exception.
You have two ways to recover:
| Operator | What it does | Typical use |
|---|---|---|
| `retry` | Resubscribes to the source after an error | Network glitches, flaky servers |
| `catchError` | Replaces the failed stream with a new observable | Fallback values, mapping errors, rethrowing |
catchError Must Return an Observable
catchError receives the error and the caught source. It must return an observable. Here are the three common choices:
of(value)emits a fallback value and then completes.EMPTYcompletes without emitting anything.throwError(() => newError)passes a different error, usually a friendlier one, on to the next handler.
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, retry, throwError, timer } from 'rxjs';
export interface Order {
id: number;
total: number;
}
@Injectable({ providedIn: 'root' })
export class OrderService {
private http = inject(HttpClient);
getOrders(): Observable<Order[]> {
return this.http.get<Order[]>('/api/orders').pipe(
retry({
count: 3,
delay: (error: HttpErrorResponse, attempt) =>
error.status >= 500 || error.status === 0
? timer(attempt * 1000)
: throwError(() => error),
}),
catchError((error: HttpErrorResponse) =>
throwError(() => new Error(`Could not load orders (status ${error.status})`))
)
);
}
}The delay callback in retry decides whether to try again. A 5xx response or status 0, which means a network failure, is retried after 1, 2, and then 3 seconds. A 4xx response is rethrown at once, because sending a bad request again will not fix it. After that, catchError replaces the raw HttpErrorResponse with a message the component can show.
Where You Catch Changes What Survives
The position of catchError decides how much of the pipeline is replaced. In the example below, an error in the middle of a stream kills the source if you catch it at the outer level:
import { of, map, catchError } from 'rxjs';
of(1, 2, 0, 4)
.pipe(
map(n => {
if (n === 0) throw new Error('zero');
return 10 / n;
}),
catchError(() => of(-1))
)
.subscribe({
next: v => console.log(v),
complete: () => console.log('complete'),
});
// 10, 5, -1, complete (4 is never processed)The source is swapped for of(-1), so the value 4 is lost. To keep a long-lived stream alive, such as form input or route changes, catch errors on the inner request, not on the outer stream. The next chapter applies this rule to flattening operators.
Exercise
A component's request uses .pipe(catchError(() => of([])), retry(2)). The server returns 503. How many requests are sent, and what does the subscriber receive?
Show answer
One request is sent. catchError turns the error into of([]), so retry never sees an error and never resubscribes. The subscriber receives [] and then complete. Swap the two operators to get up to three attempts.
Exercise
Why should retry skip 404 responses?
Show answer
A 404 means the resource does not exist. Repeating the same request will return the same answer, so retrying only adds delay and server load. Retry only transient failures such as 5xx responses or network errors (status 0).