Sub topic 7
Handling Errors and Retrying Requests
This chapter assumes you already have a TodoService that injects HttpClient and returns typed Observables from get, post, put and delete, as built in earlier chapters. It also assumes you know how pipe works and that you are comfortable with HTTP status codes. Here you will learn what Angular hands you when a request fails, how to recover or rethrow with catchError, and how to retry safely with retry.
What a Failed Request Looks Like
Every failure from HttpClient reaches you as an HttpErrorResponse. It arrives on the Observable's error channel, so it goes to the error callback of subscribe or to a catchError operator. No value is emitted and the Observable does not complete normally.
HttpErrorResponse covers two different kinds of failure:
- Network or client-side failures. The request never got a usable response. The cause might be a dropped connection, a DNS failure, a CORS rejection or a request blocked by the browser. In these cases
statusis0. - Server error responses. The server answered with a non-2xx status such as 404, 422 or 503.
statusholds that code anderrorholds the response body.
The fields you will use most:
| Field | Meaning | Typical value |
|---|---|---|
| `status` | HTTP status code, or `0` if there was no response | `0`, `404`, `500` |
| `statusText` | Status text from the server, often unreliable under HTTP/2 | `"Not Found"` |
| `error` | Parsed error body, or the underlying error for network failures | `{ message: "..." }` or a `ProgressEvent` |
| `message` | A message Angular generates, including the URL and status | `"Http failure response for /api/todos/9: 404 Not Found"` |
| `url` | The URL that failed | `"/api/todos/9"` |
| `ok` | Always `false` on an error | `false` |
| `headers` | Response headers, if a response arrived | `HttpHeaders` |
The status 200 error
One case catches many people out. Suppose the server returns 200 OK but the body is not valid JSON, for example an HTML login page served by a proxy. HttpClient then fails to parse the body and emits an HttpErrorResponse with status: 200 and ok: false. In that case error is an object with two properties: error, which holds the SyntaxError, and text, which holds the raw body. If your error handler assumes that every status below 400 means success, it will mishandle this case.
Catching Errors with catchError
catchError intercepts the error notification and must return a new Observable. That return value decides what the subscriber sees next:
- Rethrow with
throwError(() => err)so the caller still receives an error, usually a cleaner one. - Recover with a fallback value such as
of([])so the caller receives a normal value and a completion. - Swallow with
EMPTYso the caller gets a completion and no value.
Rethrowing is the right default for a data service. The service knows how to describe the failure, and the component knows how to show it to the user. Recovering inside the service hides failures from every caller, so use it only when a fallback really is correct everywhere the method is used.
The service below turns raw HttpErrorResponse objects into a small application error type. Components then never have to inspect HTTP details.
// todo-errors.ts
import { HttpErrorResponse } from '@angular/common/http';
export type TodoErrorKind = 'network' | 'not-found' | 'validation' | 'server' | 'unknown';
export class TodoError extends Error {
constructor(
readonly kind: TodoErrorKind,
message: string,
readonly cause?: HttpErrorResponse
) {
super(message);
this.name = 'TodoError';
}
}
export function toTodoError(error: HttpErrorResponse): TodoError {
if (error.status === 0) {
return new TodoError('network', 'Cannot reach the server. Check your connection.', error);
}
if (error.status === 404) {
return new TodoError('not-found', 'That todo no longer exists.', error);
}
if (error.status === 400 || error.status === 422) {
const detail = typeof error.error?.message === 'string' ? error.error.message : 'Invalid data.';
return new TodoError('validation', detail, error);
}
if (error.status >= 500) {
return new TodoError('server', 'The server had a problem. Try again later.', error);
}
return new TodoError('unknown', 'Something went wrong.', error);
}Use it in the service:
// todo.service.ts (excerpt)
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
import { Todo } from './todo.model';
import { toTodoError } from './todo-errors';
@Injectable({ providedIn: 'root' })
export class TodoService {
private readonly http = inject(HttpClient);
private readonly baseUrl = '/api/todos';
getTodo(id: number): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`).pipe(
catchError(err => throwError(() => toTodoError(err)))
);
}
}Always pass a factory function to throwError, as in throwError(() => err). The older form, throwError(err), is deprecated in RxJS 7.
Retrying with retry
HttpClient Observables are cold. Each subscription sends a new request. retry takes advantage of this: when an error arrives, it resubscribes to the source, which sends the request again.
The simplest form is retry(2), which makes up to three attempts in total. It retries immediately and treats every error the same, and both of those behaviours are usually wrong:
- An immediate retry after a 503 tends to hit the same overloaded server again.
- Retrying a 404 or 422 never helps, because the request itself is wrong.
RxJS 7.3 and later accept a configuration object. Its delay function receives the error and the retry number. It returns a notifier Observable to schedule the next attempt, or throws to stop retrying.
// retry-strategy.ts
import { HttpErrorResponse } from '@angular/common/http';
import { MonoTypeOperatorFunction, retry, throwError, timer } from 'rxjs';
const RETRYABLE = new Set([0, 408, 429, 502, 503, 504]);
export function retryTransient<T>(maxRetries = 3, baseDelayMs = 500): MonoTypeOperatorFunction<T> {
return retry<T>({
count: maxRetries,
delay: (error, retryCount) => {
if (!(error instanceof HttpErrorResponse) || !RETRYABLE.has(error.status)) {
return throwError(() => error); // stop retrying, pass the error on
}
const backoff = baseDelayMs * 2 ** (retryCount - 1); // 500, 1000, 2000 ms
const jitter = Math.random() * 100;
return timer(backoff + jitter);
}
});
}Then combine it with error mapping:
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(this.baseUrl).pipe(
retryTransient(3),
catchError(err => throwError(() => toTodoError(err)))
);
}The jitter adds a small random delay. Without it, many clients that failed at the same moment would retry at the same moment and overload the server again.
Operator order matters
Errors flow down the pipe, so the order of operators changes behaviour:
retrythencatchError: the request is retried first, andcatchErrorsees only the final failure. This is what you usually want.catchErrorthenretry:catchErrorhandles the first error. If it recovers with a fallback,retrynever sees an error and never retries. If it rethrows,retryresubscribes to everything above it, including the HTTP call.
When Not to Retry
Retrying resends the whole request. For GET, PUT and DELETE, sending the request twice should leave the server in the same state, because those methods are idempotent by HTTP semantics. POST and PATCH are not guaranteed to be idempotent. Suppose a POST /api/todos times out after the server has already saved the todo. A retry then creates a duplicate.
Retry a mutation only when one of these is true:
- The API supports an idempotency key, such as an
Idempotency-Keyheader, that it uses to remove duplicates. - The failure clearly happened before the server processed the request. Status
0caused by being offline is the best-known example, but you cannot always tell it apart from a dropped response.
Handling the Error in the Component
The component subscribes and reacts to the clean TodoError:
// todo-detail.component.ts
import { Component, inject, input, signal, OnInit } from '@angular/core';
import { TodoService } from './todo.service';
import { Todo } from './todo.model';
import { TodoError } from './todo-errors';
@Component({
selector: 'app-todo-detail',
template: `
@if (todo(); as t) {
<h2>{{ t.title }}</h2>
} @else if (errorMessage()) {
<p role="alert">{{ errorMessage() }}</p>
} @else {
<p>Loading...</p>
}
`
})
export class TodoDetailComponent implements OnInit {
private readonly todoService = inject(TodoService);
readonly id = input.required<number>();
readonly todo = signal<Todo | null>(null);
readonly errorMessage = signal<string | null>(null);
ngOnInit(): void {
this.todoService.getTodo(this.id()).subscribe({
next: t => this.todo.set(t),
error: (err: TodoError) => this.errorMessage.set(err.message)
});
}
}If you subscribe without an error callback and nothing upstream catches the error, RxJS reports it as an unhandled error, which by default is rethrown asynchronously. The same rule applies to the async pipe and toSignal: an unhandled error is thrown while the template is read, so catch errors in the service or in the component's stream. The chapter on showing API data covers those consumers.
Edge Cases Worth Knowing
- Errors end the stream. After an error, the Observable is finished. If a
catchErroris placed inside a long-lived stream, such as one built withswitchMapover search terms, put it on the inner HTTP Observable. Otherwise one failure stops the whole outer stream. - The error body type varies. When you request
responseType: 'blob'or'text',error.errorcomes back as aBlobor a string, not parsed JSON. Check the type before you read fields from it. - Timeouts are not built in.
HttpClienthas no default timeout. Add the RxJStimeout(10_000)operator beforeretryif you want slow requests to fail. Note thattimeoutemits aTimeoutError, not anHttpErrorResponse, soretryTransientas written will not retry it. - Centralising the handling. Mapping errors in every method gets repetitive. A later chapter moves shared logic such as logging, or redirecting on 401, into a functional interceptor. Mapping that belongs to one specific domain, such as todos, usually stays in the service.
Exercise
A request is written as this.http.get<Todo[]>(url).pipe(catchError(() => of([])), retry(3)). The server returns 503 every time. How many HTTP requests are sent, and what does the subscriber receive?
Show answer
Exactly one request is sent. catchError handles the first 503 and replaces it with of([]), which emits an empty array and completes. retry never sees an error, so it never resubscribes. The subscriber receives [] followed by completion. To retry first, put retry(3) before catchError.
Exercise
Your API sometimes returns 200 OK with an HTML maintenance page. Your catchError handler logs "Success status but failed". Explain why that handler ran, and which properties of the error tell you what happened.
Show answer
HttpClient expected JSON and failed to parse the HTML, so it emitted an HttpErrorResponse with status: 200 and ok: false. In that case error.error is an object whose error property holds the SyntaxError and whose text property holds the raw HTML body.
Exercise
Why is it risky to apply retryTransient() to addTodo, which sends a POST, and what would make it safe?
Show answer
POST is not idempotent. If the server saved the todo but the response was lost, a retry creates a duplicate. It becomes safe if the API accepts an idempotency key, sent as a header that stays the same across retries, which lets the server spot and ignore duplicate submissions.