Sub topic 7
Handling Errors with catchError and retry
This chapter assumes you already know how to build pipelines with pipe, map, and tap, and how to call HttpClient from a service. It covers what happens to a stream when something fails, how to replace a failed stream with catchError, how to try again with retry, and how to combine the two so that a component always receives something useful.
What an error does to a stream
An observable can send three kinds of notification: next, error, and complete. error and complete are both terminal. Once a stream errors, it emits nothing more, and every operator downstream of the failure unsubscribes from its source.
This is the single most important fact about RxJS errors. You cannot "skip" a failed value and carry on in the same stream. The original stream is finished, and all you can do is decide what to put in its place.
import { of, map, catchError } from 'rxjs';
of(1, 2, 3)
.pipe(
map(n => {
if (n === 2) {
throw new Error('bad value');
}
return n;
}),
catchError(() => of(-1))
)
.subscribe({
next: value => console.log(value),
complete: () => console.log('complete'),
});
// Output:
// 1
// -1
// completeThe value 3 never appears. The exception thrown inside map became an error notification, which ended the of(1, 2, 3) stream. catchError then subscribed to of(-1), and that replacement stream emitted once and completed.
catchError: replacing a failed stream
catchError takes a function (error, caught) => ObservableInput. Whatever observable that function returns becomes the continuation of the stream. You have three common choices.
| Return value | Effect downstream | Typical use |
|---|---|---|
| `of(fallback)` | Emits the fallback, then completes | Show an empty list or a default config |
| `EMPTY` | Completes with no value | Silently drop an optional enhancement |
| `throwError(() => err)` | Errors again, possibly with a new error | Log or translate the error, then let the caller decide |
The second argument, caught, is the source observable itself. Returning it resubscribes to the source, which is a crude retry with no limit. Prefer retry, which has a count and a delay.
Translating HttpClient errors
HttpClient errors with an HttpErrorResponse. Its status field tells you what went wrong:
0means the request never got a response: network failure, CORS rejection, or a request that was aborted.4xxmeans the client sent something the server rejected, such as a 404 or 401.5xxmeans the server failed while handling the request.
A service is a good place to turn these into errors that the rest of the app understands, while leaving the fallback decision to the component.
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
export interface Order {
id: number;
total: number;
}
export class OrderLoadError extends Error {
constructor(
message: string,
readonly retryable: boolean
) {
super(message);
}
}
@Injectable({ providedIn: 'root' })
export class OrderService {
private http = inject(HttpClient);
getOrders(): Observable<Order[]> {
return this.http.get<Order[]>('/api/orders').pipe(
catchError((err: HttpErrorResponse) => {
const retryable = err.status === 0 || err.status >= 500;
const message =
err.status === 0
? 'Network unavailable'
: `Server responded with ${err.status}`;
return throwError(() => new OrderLoadError(message, retryable));
})
);
}
}throwError takes a factory function, () => err, rather than the error itself. Passing the error directly is deprecated in RxJS 7 and later.
retry: subscribing again
retry responds to an error by unsubscribing from the source and subscribing to it again. The effect depends on whether the source is cold. HttpClient observables are cold, so each new subscription sends a fresh HTTP request. That is why retry works for HTTP calls.
retry(n) allows up to n resubscriptions, which means n + 1 attempts in total. The next example shows the count without a server.
import { defer, of, throwError, retry } from 'rxjs';
let attempts = 0;
const flaky$ = defer(() => {
attempts++;
console.log(`attempt ${attempts}`);
return attempts < 3 ? throwError(() => new Error('fail')) : of('ok');
});
flaky$.pipe(retry(2)).subscribe({
next: value => console.log(value),
error: err => console.log('gave up:', err.message),
});
// Output:
// attempt 1
// attempt 2
// attempt 3
// okdefer runs its factory on every subscription, which is how it imitates a cold HTTP request. With retry(1) you would see two attempts followed by gave up: fail.
Delays, backoff, and choosing what to retry
Retrying immediately against a server that is struggling just adds to its load. The configuration form retry({ count, delay }) takes a delay function (error, retryCount) => ObservableInput. The retry happens when the returned observable emits. If it errors instead, the error is passed downstream and retrying stops. That lets you build exponential backoff and skip errors that will never succeed.
import { Observable, retry, throwError, timer } from 'rxjs';
import { OrderLoadError } from './order.service';
export function retryWithBackoff<T>(maxRetries = 3, baseMs = 500) {
return (source: Observable<T>) =>
source.pipe(
retry({
count: maxRetries,
delay: (error, retryCount) => {
if (error instanceof OrderLoadError && !error.retryable) {
return throwError(() => error);
}
return timer(baseMs * 2 ** (retryCount - 1));
},
})
);
}retryCount starts at 1, so the waits are 500 ms, 1000 ms, and 2000 ms. A 404 is marked non-retryable and fails at once. Retrying it would only delay the same answer.
Ordering: retry before catchError
Operators see only what comes from upstream. If catchError comes before retry and returns a fallback, the error never reaches retry, and no retry happens. The usual order is: transform the error, retry, then fall back.
Here is the full pattern in a component. It also uses finalize, which runs on error, on completion, or on unsubscribe, to clear a loading flag.
import { Component, inject, signal } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, catchError, finalize, of } from 'rxjs';
import { Order, OrderService } from './order.service';
import { retryWithBackoff } from './retry-with-backoff';
@Component({
selector: 'app-orders',
standalone: true,
imports: [AsyncPipe],
template: `
@if (loading()) {
<p>Loading…</p>
}
@if (errorMessage()) {
<p class="error">{{ errorMessage() }}</p>
}
@if (orders$ | async; as orders) {
<ul>
@for (order of orders; track order.id) {
<li>#{{ order.id }}: {{ order.total }}</li>
}
</ul>
}
`,
})
export class OrdersComponent {
private orderService = inject(OrderService);
loading = signal(true);
errorMessage = signal('');
orders$: Observable<Order[]> = this.orderService.getOrders().pipe(
retryWithBackoff(3, 500),
catchError((err: Error) => {
this.errorMessage.set(err.message);
return of([]);
}),
finalize(() => this.loading.set(false))
);
}Edge cases and common mistakes
Catching at the wrong level of a long-lived stream
For a one-shot HTTP call, catching at the end of the pipeline is fine because the stream was going to complete anyway. For a long-lived source such as form valueChanges that feeds a request per value, a catchError at the outer level replaces the entire source with the fallback. The fallback completes, and later keystrokes do nothing. The fix is to catch inside the inner request so that only that request is replaced. The next chapter covers inner observables in detail.
Retrying hot or side-effecting sources
retry resubscribes. If the source is hot, for example a shared stream or a Subject, resubscribing does not repeat the work, and you may just wait for the next value. If the source has side effects, such as a POST that creates an order, a retry can perform the side effect twice. Retry non-idempotent requests only when the server deduplicates them, for example with an idempotency key.
Swallowing errors silently
Returning EMPTY or of([]) without logging or telling the user makes failures look like "no data". Record the error or set a state that the user can see, as errorMessage does above.
Errors thrown in subscribe callbacks
An exception thrown inside your own next handler is not routed to catchError, because it happens after the pipeline has finished its work. Do work that might throw inside an operator such as map so the pipeline can catch it.
Exercise
A teammate writes http.get('/api/items').pipe(catchError(() => of([])), retry(3)). The server returns a 503. How many requests are sent, and what does the subscriber receive?
Show answer
One request. catchError comes first, turns the error into of([]), and that stream emits [] and completes normally. retry never sees an error, so it never resubscribes. Swap the operators to retry(3) and then catchError(...) to get up to four attempts before the fallback.
Exercise
Using retry({ count, delay }), write a pipeline for http.get<string[]>('/api/tags') that retries up to 2 times with a fixed 1-second delay, only for status 0 or 5xx, and falls back to an empty array.
Show answer
http.get<string[]>('/api/tags').pipe(retry({ count: 2, delay: (err: HttpErrorResponse) => (err.status === 0 || err.status >= 500) ? timer(1000) : throwError(() => err) }), catchError(() => of([]))). A 4xx error is rethrown from the delay function, so retrying stops at once and catchError supplies [].
Exercise
Why does retry send a new HTTP request each time, and why would the same operator not re-run the work on a stream backed by a Subject?
Show answer
HttpClient observables are cold. Each subscription runs the producer, which sends a request, so resubscribing repeats the request. A Subject is hot: subscribing again only attaches a new listener to a producer that already exists, so nothing is re-executed. Also, a Subject that has errored will immediately send that same error to any new subscriber.