Handling Errors Globally
Catch and transform HTTP errors centrally.
Central error handling
Instead of catching HTTP errors in every component, an interceptor can handle them globally: log them, show a toast, redirect on 401, or normalize the error shape.
catchError in an interceptor
Pipe the next(req) stream through catchError to intercept failures.
import { catchError, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
catchError((err: HttpErrorResponse) => {
console.error('HTTP error', err.status);
return throwError(() => err);
})
);All lessons in this course
- Functional Interceptors
- Adding Auth Headers
- Handling Errors Globally
- Retry and Loading Indicators