0 day streak
javascript / intermediate
Snippet

Intercepting and Transforming HTTP Errors with Functional Interceptors

Functional HTTP interceptors (`HttpInterceptorFn`) allow capturing backend network exceptions and normalizing them into a predictable application-specific error data structure. This decouples individual UI services from low-level `HttpErrorResponse` structures.

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
26
27
28
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export interface AppError {
statusCode: number;
friendlyMessage: string;
}
export const errorTransformInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
let friendlyMessage = 'An unexpected error occurred.';
if (error.status === 404) {
friendlyMessage = 'The requested resource was not found.';
} else if (error.status === 403) {
friendlyMessage = 'You do not have permission to perform this action.';
}
const appError: AppError = {
statusCode: error.status,
friendlyMessage
};
return throwError(() => appError);
})
);
};
angular
Breakdown
1
export const errorTransformInterceptor: HttpInterceptorFn = (req, next) => {
Defines a standalone functional interceptor handling outgoing requests and incoming responses.
2
catchError((error: HttpErrorResponse) => {
Catches upstream HTTP failure events within the RxJS pipeline.
3
return throwError(() => appError);
Rethrows the standardized domain error object using a factory function to subscribers.