0 Tage Serie
javascript / intermediate
Snippet

Globale HTTP-Fehlerbehandlung mittels funktionaler Interzeptoren

Funktionale HTTP-Interzeptoren fangen ausgehende Anfragen und eingehende Antworten ab, ohne dass Klassen-Boilerplate erforderlich ist. Durch das Anwenden des catchError-Operators auf den Handler können HTTP-Statusfehler und clientseitige Netzwerkfehler normalisiert, an einen Benachrichtigungsdienst weitergeleitet und für nachgelagerte Subscriber erneut ausgelöst werden.

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
Erklärung
1
export const errorHandlingInterceptor: HttpInterceptorFn = (req, next) => {
Deklariert einen funktionalen HTTP-Interzeptor gemäß dem HttpInterceptorFn-Typvertrag von Angular.
2
const notifier = inject(NotificationService);
Löst die NotificationService-Abhängigkeit im funktionalen Injection-Kontext auf.
3
catchError((error: HttpErrorResponse) => {
Fängt Netzwerk- oder HTTP-Statusfehler ab, die vom nachfolgenden Handler ausgegeben werden.
4
if (error.error instanceof ErrorEvent) {
Unterscheidet clientseitige JavaScript-/Netzwerkfehler von Backend-HTTP-Statuscodes.
5
return throwError(() => error);
Wirft den ursprünglichen Fehler erneut, damit aufrufende Stellen über das Scheitern informiert bleiben.