javascript / intermediate
Snippet
Handling Global HTTP Errors via Functional Interceptors
Functional HTTP interceptors capture outgoing requests and incoming responses without requiring class boilerplate. By piping the catchError operator onto the forward handler, intermediate HTTP error codes and client-side network failures can be normalized, dispatched to an alert mechanism, and rethrown for downstream subscriber visibility.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';import { inject } from '@angular/core';import { catchError, throwError } from 'rxjs';import { NotificationService } from './notification.service';export const errorHandlingInterceptor: HttpInterceptorFn = (req, next) => {const notifier = inject(NotificationService);return next(req).pipe(catchError((error: HttpErrorResponse) => {let message = 'An unexpected server error occurred.';if (error.status === 404) {message = 'The requested resource was not found.';} else if (error.status === 403) {message = 'Access denied. You lack the required permissions.';} else if (error.error instanceof ErrorEvent) {message = `Client error: ${error.error.message}`;}notifier.showError(message);return throwError(() => error);}));};
angular
Breakdown
1
export const errorHandlingInterceptor: HttpInterceptorFn = (req, next) => {
Declares a functional HTTP interceptor conforming to Angular's modern HttpInterceptorFn contract.
2
const notifier = inject(NotificationService);
Resolves the notification service dependency within the interceptor's functional injection context.
3
catchError((error: HttpErrorResponse) => {
Catches any network or HTTP status failure emitted by the downstream handler.
4
if (error.error instanceof ErrorEvent) {
Distinguishes client-side JavaScript/network exceptions from upstream backend HTTP status codes.
5
return throwError(() => error);
Rethrows the original error to ensure callers remain aware of the failure state.