繁体   English   中英

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

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

我对使用侦听ErrorHandler来处理Angular 6+中HTTP请求的自定义错误和客户端错误的方法进行了澄清。

正确调用客户端错误。 但是对于HTTP错误,当添加了HTTP请求订阅者的错误处理程序时,不会调用自定义错误处理程序(请参见以下代码)。 从订户中删除错误处理程序时,将同时调用自定义错误处理程序。 那是预期的行为。 在Angular文档中找不到与此文档相关的任何文档。

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

谢谢,

彼得

你可以有一个HttpInterceptor

在内部,您会捕获不同类型的错误。

像这个 :

@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