Sub topic 3
Centralized Error Handling and Retry in Angular HTTP Interceptors
Assume you know TypeScript, Angular dependency injection, HttpClient, Observables, pipe, tap, and catchError.
Centralized error handling and retry
An interceptor can observe failures in one place, log them, or retry temporary failures. Always rethrow errors that the caller still needs to handle.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, retry, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
retry({ count: 2, delay: 500 }),
catchError((error: HttpErrorResponse) => {
console.error(`HTTP ${error.status}: ${error.message}`);
return throwError(() => error);
}),
);Retry only safe, temporary failures. Retrying a POST can create duplicate data unless the server supports idempotency.
Controlling behavior with `HttpContext`
HttpContextToken provides per-request options without special URLs or headers.
import { HttpContext, HttpContextToken } from '@angular/common/http';
export const SKIP_ERROR_LOG = new HttpContextToken<boolean>(() => false);
// In an interceptor:
// if (req.context.get(SKIP_ERROR_LOG)) return next(req);
// In a service:
this.http.get('/api/health', {
context: new HttpContext().set(SKIP_ERROR_LOG, true),
});Testing with `HttpTestingController`
Register the interceptor, issue a request, then inspect the request captured by the testing controller.
const http = TestBed.inject(HttpClient);
const controller = TestBed.inject(HttpTestingController);
http.get('/api/data').subscribe();
const request = controller.expectOne('/api/data');
expect(request.request.headers.get('Authorization')).toBe('Bearer abc');
request.flush({});
controller.verify();flush completes the fake response. Use request.flush(errorBody, options) to test failures.
Class-based interceptors
Older applications use classes registered with the HTTP_INTERCEPTORS multi-provider. Enable them with withInterceptorsFromDi(). New code generally prefers functional interceptors because registration and dependencies are more visible.
Refreshing an expired token
A 401 interceptor can call a refresh endpoint, store the new token, and retry the original request. Coordinate concurrent 401 responses so they share one refresh operation. Do not retry forever, and exclude the refresh request from the authentication interceptor.
Common pitfalls and limits
- Forgetting
next(req)stops the request. - Mutating
HttpRequestdirectly does nothing. Useclone(). - Interceptors affect requests made through
HttpClient, notfetch, images, or other libraries. - Logging tokens or sensitive response bodies can leak secrets.
- Retry policies must consider request safety and server load.
Exercise
Why should an interceptor rethrow an error after logging it?
Show answer
Rethrowing preserves the error for the original caller, which may need to display a message or perform recovery.