简体   繁体   English

Angular-用于自定义HTTP错误处理的拦截器的ErrorHandler

[英]Angular - ErrorHandler for interceptor for custom HTTP error handling

I had a clarification on usage of intercepting ErrorHandler for handling custom error for HTTP requests and client side errors in Angular 6+. 我对使用侦听ErrorHandler来处理Angular 6+中HTTP请求的自定义错误和客户端错误的方法进行了澄清。

Its getting called correctly for client side errors. 正确调用客户端错误。 But for HTTP errors custom error handler not getting called when there is a error handler added HTTP request subscriber(See below code). 但是对于HTTP错误,当添加了HTTP请求订阅者的错误处理程序时,不会调用自定义错误处理程序(请参见以下代码)。 Same time custom error handler get called when error handler removed from subscriber. 从订户中删除错误处理程序时,将同时调用自定义错误处理程序。 Is that expected behavior. 那是预期的行为。 Couldn't find any doc related to that in Angular doc. 在Angular文档中找不到与此文档相关的任何文档。

.subscribe(
  success => {
    this.processGetChart(success);
  },
  error => {
    this.errors = error;
    console.log('API Error: ', error);
  },
  () => {
  }
  );

Thanks, 谢谢,

Peter 彼得

You can have an HttpInterceptor 你可以有一个HttpInterceptor

And inside, you catch the different types of error. 在内部,您会捕获不同类型的错误。

like this one : 像这个 :

@Injectable()
export class customInterceptor implements HttpInterceptor {

  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      tap((event: HttpEvent<any>) => {
        }, (err: any) => {
          if (err instanceof HttpErrorResponse) {
            if (err.status === 403 || err.status === 401) {
              // DO SOMETHING HERE.
            }
          }
        }
      )
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM