简体   繁体   中英

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+.

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). 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.

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

Thanks,

Peter

You can have an 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.
            }
          }
        }
      )
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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