Sub topic 7
Handling Errors and Retrying Requests
This chapter assumes you already have a TodoService that injects HttpClient and returns typed Observables, as built in the earlier chapters. You should also know how pipe chains RxJS operators.
Requests fail. The network drops, the server crashes, or the API rejects bad input. HttpClient reports every one of these failures the same way. The Observable emits an error notification carrying an HttpErrorResponse. Your job is to decide which failures to retry, which to report, and what the caller sees.
What an HttpErrorResponse Contains
An HttpErrorResponse is the object HttpClient passes to the error channel. These are the fields you will read most often:
| Property | Meaning |
|---|---|
| `status` | The HTTP status code, or `0` if no response arrived |
| `statusText` | The status message sent by the server |
| `error` | The response body for server errors, or a `ProgressEvent` for network errors |
| `url` | The URL of the request that failed |
| `message` | A summary string generated by Angular |
There are two kinds of failure. A status of 0 means the request never got a response. The cause may be a lost connection, a CORS rejection or a DNS failure. Any other status means the server answered with an error code such as 404 or 500.
Retrying and Catching
The usual pattern puts retry before catchError in the pipe:
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, retry, throwError } from 'rxjs';
// Inside TodoService
getTodoSafely(id: number): Observable<Todo> {
return this.http.get<Todo>(`${this.baseUrl}/${id}`).pipe(
retry(2),
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
console.error('Network error:', error.error);
} else {
console.error(`Server returned ${error.status}:`, error.error);
}
return throwError(() => new Error('Could not load the todo.'));
})
);
}retry(2) resubscribes to the source Observable when it errors. Each resubscription sends a new HTTP request because HttpClient Observables are cold. In this example the request can run up to three times. catchError sees the error only after every retry has failed. It logs the details and rethrows a plain Error, so components never need to know about HttpErrorResponse.
Retrying Only What Makes Sense
Retrying immediately and unconditionally is often wrong. A 404 or 400 will fail the same way every time. You can pass a config object to retry that sets a delay and filters by status:
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, retry, throwError, timer } from 'rxjs';
// Inside TodoService
getTodosWithBackoff(page: number): Observable<Todo[]> {
return this.getTodos(page).pipe(
retry({
count: 3,
delay: (error: HttpErrorResponse, retryCount: number) => {
const transient = error.status === 0 || error.status >= 500;
if (!transient) {
return throwError(() => error);
}
return timer(retryCount * 1000);
}
})
);
}The delay function returns an Observable. When it emits, retry tries again. When it errors, retrying stops and the error moves down the pipe. In this example the waits grow from 1 to 2 to 3 seconds. Only network errors and 5xx responses get retried.
Choosing What catchError Returns
The Observable that catchError returns decides what the subscriber sees next:
throwError(() => err)passes an error on. The caller still has to handle it.of(fallback)replaces the error with a value, such as an empty array. The stream completes normally.EMPTYcompletes without emitting anything.
Return a fallback when the UI can reasonably carry on without the data. Rethrow when the caller needs to show an error state. To handle errors the same way for every request, use an interceptor, which a later chapter covers.
Exercise
A component calls a service method piped through retry(2) and then catchError(() => of([])). The server returns 404 every time. How many HTTP requests are sent, and what does the subscriber receive?
Show answer
Three requests are sent: the original and two retries, because plain retry(2) does not check the status code. After the third failure, catchError replaces the error with of([]). The subscriber receives an empty array and then a completion notification, with no error.
Exercise
Why is retry placed before catchError in the pipe rather than after it?
Show answer
catchError turns the error into something else: a fallback value or a new error. If it came first, retry would see either no error at all or the already-converted error. Putting retry first means the original request is retried, and catchError runs only once every attempt has failed.