Sub topic 3
Functional Interceptors with `withInterceptors`
This chapter assumes you know Angular services, HttpClient, and RxJS pipe(). An interceptor is a function that can inspect or change every HTTP request and response.
Registering a Functional Interceptor
Angular registers functional interceptors with withInterceptors. Registration in the application configuration applies the interceptor to every HttpClient request.
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { retryInterceptor } from './retry.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([retryInterceptor])),
],
};Building a Retry Interceptor
Retry only operations that are safe to repeat. A GET request usually is safe. A POST request might create duplicate data, so this interceptor leaves it unchanged.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const transient = new Set([0, 408, 429, 500, 502, 503, 504]);
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (req.method !== 'GET') return next(req);
return next(req).pipe(
retry({
count: 3,
delay: (error: unknown, attempt: number) => {
if (!(error instanceof HttpErrorResponse) ||
!transient.has(error.status)) {
return throwError(() => error);
}
return timer(500 * 2 ** (attempt - 1));
},
})
);
};The delays are 500 ms, 1 second, and 2 seconds. This exponential backoff reduces pressure on a failing server.
Adding Timeouts
A timeout prevents a request from waiting forever. Add the RxJS timeout operator before retry logic when slow connections should fail.
import { timeout } from 'rxjs';
return next(req).pipe(timeout(5000), retry({ count: 2 }));Reporting Unhandled Errors
Use Angular’s ErrorHandler for errors that reach the application without a local handler. It can log errors or send them to monitoring.
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
console.error('Unhandled error:', error);
}
}Testing Failures and Retries
HttpTestingController replaces the real server in tests. It lets you flush errors and verify retry behavior.
const request = httpMock.expectOne('/api/users/1');
request.flush('Unavailable', { status: 503, statusText: 'Service Unavailable' });
httpMock.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });Call httpMock.verify() in afterEach so unexpected requests fail the test.
Handling 401 Responses
A 401 response means authentication is missing or expired. An authentication interceptor can refresh the token, clone the request with the new token, and call next again. Prevent infinite loops by excluding the refresh endpoint and retrying the original request only once.
Exercise
Why should a retry interceptor usually exclude POST requests?
Show answer
Repeating a POST can create duplicate records or repeat another side effect.