Sub topic 10
Centralized error handling and retry
This chapter assumes you can write a functional interceptor, register it with withInterceptors, and use pipe, tap and catchError from RxJS. Here you handle failed requests in one place instead of in every subscribe call.
Why handle errors in an interceptor
Without an interceptor, each component repeats the same error code for network failures, expired sessions and server faults. An interceptor sees every response that comes back through HttpClient, so it can log, translate or retry failures once.
The observable returned by next(req) errors with an HttpErrorResponse when the request fails. That covers non-2xx statuses and network failures. A network failure has status === 0.
Observe and rethrow
This interceptor logs the failure and rethrows it:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
console.error('Network error', error.error);
} else {
console.error(`Server returned ${error.status}`, error.message);
}
return throwError(() => error);
}),
);
};The last line matters. If catchError returned a normal value, the caller would see a successful response and never learn that the request failed. Rethrowing lets a component still show its own message or fall back to cached data.
Retry transient failures
Some failures are temporary: a dropped connection or a 503 from an overloaded server. RxJS retry can resubscribe to next(req), which sends the request again. Its delay option takes a function that receives the error and the retry count. It returns an observable that decides when to retry. If that observable errors, retrying stops and the error passes on.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const RETRYABLE = new Set([0, 502, 503, 504]);
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') {
return next(req);
}
return next(req).pipe(
retry({
count: 2,
delay: (error: HttpErrorResponse, retryCount: number) =>
RETRYABLE.has(error.status)
? timer(retryCount * 500)
: throwError(() => error),
}),
);
};The interceptor retries only GET requests, because repeating a POST could create a duplicate order or payment. It waits 500 ms before the first retry and 1000 ms before the second. A 404 or 401 is not in the set, so it fails immediately.
Order the two interceptors
Place retry before the error logger in the array, so that the logger sees only the final failure:
provideHttpClient(withInterceptors([authInterceptor, errorInterceptor, retryInterceptor]));Requests travel through the array in order and responses come back in reverse. The error from the backend therefore reaches retryInterceptor first. If it retries and the request then succeeds, errorInterceptor never sees an error. If all retries fail, it logs one error rather than three.
Common mistakes
- Returning a value from
catchErrorinstead of rethrowing, which hides the failure from the caller. - Retrying non-idempotent methods such as
POST. - Retrying 4xx errors. Repeating a bad request gives the same result.
- Retrying with no delay, which can overload a server that is already struggling.
Exercise
A GET request fails with a 404. With the retry interceptor above placed after the error interceptor in the array, how many times is the request sent, and what does the caller receive?
Show answer
It is sent once. The 404 is not in the RETRYABLE set, so the delay function returns throwError and retry stops immediately. The error interceptor logs it and rethrows it, so the caller's error handler receives the HttpErrorResponse.