【问题标题】:Handling error in ErrorHandler and handling in HttpInterceptorErrorHandler 中的错误处理和 HttpInterceptor 中的处理
【发布时间】: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


    【解决方案1】:

    有一个类似的问题here 可能就是您要找的问题! :)

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2018-12-18
      • 1970-01-01
      • 2018-05-05
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多