import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs';
@Injectable({ providedIn: 'root' }) export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
console.error(error);
let errorMessage = 'An unknown error occurred!';
if (error.error) {
errorMessage = error.error.message;
}
window.alert(errorMessage);
return throwError(errorMessage);
})
);
}
}
记得要在app.module.ts中注册该拦截器。