Sub topic 2
Showing Error State to Users
Assume you know TypeScript, Angular services and components, RxJS Observables, and basic HttpClient requests. An HTTP failure should become visible UI state, not only a console message.
Representing the Error State
Keep loading, data, and error state separate. A component can display a message while preserving the previous data.
HttpErrorResponse describes the failure. Status 0 usually means a network or CORS failure. Statuses from 400 to 499 usually describe a client request problem. Statuses from 500 to 599 describe a server failure.
import { HttpErrorResponse } from '@angular/common/http';
export function messageFor(error: HttpErrorResponse): string {
if (error.status === 0) {
return 'The network is unavailable. Check your connection.';
}
if (error.status >= 500) {
return 'The service is temporarily unavailable. Try again later.';
}
return 'The request could not be completed.';
}Show a retry action for temporary failures, but give users a useful message instead of exposing raw status codes.
Retrying with `retry`
RxJS retry resubscribes to the source after an error. The count option limits additional attempts.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { retry, Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ProfileService {
private http = inject(HttpClient);
getProfile(): Observable<{ name: string }> {
return this.http
.get<{ name: string }>('/api/profile')
.pipe(retry({ count: 2 }));
}
}This makes up to three total requests: the original request and two retries. If all attempts fail, the final error reaches the subscriber, where the component can set its error state.
Choosing a Retry Policy
Retry only failures that are likely to be temporary and safe to repeat.
| Failure | Usually retry? | Reason |
|---|---|---|
| Network error, status 0 | Sometimes | The connection may recover |
| 408, 429, 5xx | Often | The request may succeed later |
| 400, 401, 403, 404 | Usually no | The request or permissions need correction |
Exponential Backoff
Immediate retries can overload a failing service. Exponential backoff increases the delay after each attempt, such as 500 ms, 1 s, and 2 s.
import { HttpErrorResponse } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const retryable = new Set([0, 408, 429, 500, 502, 503, 504]);
export const requestWithBackoff = <T>(source: import('rxjs').Observable<T>) =>
source.pipe(
retry({
count: 3,
delay: (error: unknown, attempt: number) => {
if (!(error instanceof HttpErrorResponse) || !retryable.has(error.status)) {
return throwError(() => error);
}
return timer(2 ** (attempt - 1) * 500);
},
}),
);Exercise
Why should a 404 response usually not be retried?
Show answer
Retrying does not change the missing URL or resource, so it adds delay without improving the result.