【发布时间】:2020-04-26 23:56:16
【问题描述】:
Angular 7 中两种错误处理方法的区别是什么。我们是否需要在 HttpInterceptor 和 Angular 的内置 ErrorHandler 中处理全局错误。请让我知道在 HttpInterceptor 中我们可以处理哪些错误类型以及在 ErrorHandler 中我们可以处理哪些错误。我们需要两者还是任何一个就足够了
export class InterceptorService implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
let errMsg = '';
if (error.error instanceof ErrorEvent) {
// Client Side Error
errMsg = `Client Error: ${error.error.message}`;
console.log(error);
}
else {
// Server Side Error
errMsg = `Server Error: ${error.status}, Message: ${error.message}`;
console.log(error);
}
return throwError(errMsg);
})
);
}
}
export class ErrorsHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error: Error | HttpErrorResponse) {
const notificationService = this.injector.get(NotificationService);
if (error instanceof HttpErrorResponse) {
// Server or connection error happened
if (!navigator.onLine) {
// Handle offline error
return notificationService.error('No Internet Connection');
} else {
// Handle Http Error
return notificationService.error(`${error.status} - ${error.message}`);
}
} else {
// Handle Client Error
notificationService.error(error.message);
}
}
}
【问题讨论】:
标签: angular exception error-handling angular-http-interceptors