What is the Angular HttpClient interceptor and error handling?
Answer
Centralized HTTP error handling in Angular uses interceptors to catch and handle errors from all HTTP requests. Error types: Client-side errors: network issues, CORS, browser preventing the request; Server-side errors: 4xx (client errors) and 5xx (server errors) status codes. Error interceptor implementation: export class ErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( catchError((error: HttpErrorResponse) => { if (error.status === 401) { this.authService.logout(); this.router.navigate(["/login"]); } else if (error.status === 403) { this.router.navigate(["/forbidden"]); } else if (error.status >= 500) { this.notificationService.showError("Server error. Please try again."); } const errorMessage = error.error?.message || error.message || "Unknown error"; return throwError(() => new Error(errorMessage)); }) ); } }. Retry logic: return next.handle(req).pipe( retry({ count: 3, delay: 1000 }), catchError(...) ). Token refresh: on 401, refresh the token and retry: pipe with catchError(err => err.status === 401 ? this.authService.refreshToken().pipe(switchMap(token => next.handle(addToken(req, token)))) : throwError(() => err)). Component-level error handling: override interceptor behavior: this.http.get("/api/data").pipe(catchError(err => { this.localError = err; return EMPTY; })).
More Angular Questions
View all →- Intermediate What is RxJS and how is it used in Angular?
- Intermediate What is the difference between switchMap, mergeMap, concatMap, and exhaustMap?
- Intermediate What is the difference between Subject, BehaviorSubject, ReplaySubject, and AsyncSubject?
- Intermediate What is the Angular NgRx state management library?
- Intermediate What is Angular lazy loading and preloading strategy?