Lesson 22 / 32
HTTP Interceptors & Error Handling
Add auth headers, logging and global error handling to every request with functional HTTP interceptors.
A functional interceptor
A functional interceptor is a function that can clone and modify each request before it is sent, and handle the response or error.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, throwError } from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).token();
const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
return next(authReq).pipe(
catchError((err) => {
if (err.status === 401) inject(AuthService).logout();
return throwError(() => err);
}),
);
};Register it
Add interceptors when providing HttpClient.
bootstrapApplication(AppComponent, {
providers: [provideHttpClient(withInterceptors([authInterceptor]))],
});Interceptors run in the order listed. Keep each one focused, and never log tokens or personal data.