1

I want to intercept each request and error responses.

I already can intercept requests and set a token in the headers and I can intercept the responses to handle a refresh token.

However I can't find a way to intercept HttpErrorResponse.

I tried 2 methods. One with an explicit rxjs catchError and the other with some kind of callback:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = this.auth.getToken();
    if (authToken) {
      req = req.clone({ headers: req.headers.set('accesstoken', authToken) });
    }
    return next.handle(req).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          //handle refresh token
        }
        return event;
      },
      catchError((error: any) => {
        if (error instanceof HttpErrorResponse) {
          console.log(error);
          return Observable.throw(error);
        }
      })));
  }

If I have an expired token, every request throws an HttpErrorResponse but this solution doesn't catch it.

enter image description here

This is returned by the service. No sign of the console.log() from the interceptor.

The service looks like this:

public getData(): Observable<any> {
    return this.http
        .get<any>(url)
        .pipe(
            map(res => {
                return res;
            }),
            catchError((e): Observable<any> => {
                console.log(e);
                const res: any = {error: e};
                return of(res);
            })
        );
}

Then I tried with a "callback syntax":

return next.handle(req).pipe(
  map((event: HttpEvent<any>) => {
    if (event instanceof HttpResponse) {
      // refresh token
    }
    return event;
  }, (error: any) => {
    if (error instanceof HttpErrorResponse) {
      console.log(error);
    }
  }));

Same result as above. Nothing in the console.

I've seen people (https://medium.com/@aleixsuau/error-handling-angular-859d529fa53a) register an ErrorHandler in the module but I haven't tried it yet.

How do I catch an HttpErrorResponse from my interceptor?

EDIT:

I've tried the ErrorHandler way but still couldn't get any log. Then I removed the catchError from my service and finally got something logged...

I'll try to see if this makes the interceptor work... Not fun if I have to remove all my catchError :(

I made a reproducible example here: https://stackblitz.com/edit/angular-m2jc9n

1 Answer 1

4

Angular has a hook for error handling (https://angular.io/api/core/ErrorHandler).

You can create a service which implements the angular ErrorHandler and implements handleError method where you can log all errors. This error handler would log not just HttpErrorResponse but all errors, but you can filter out the ones you need.

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
    private static isHttpErrorResponse(error): error is HttpErrorResponse {
        return error instanceof HttpErrorResponse;
    }

    handleError(error: any): void {
        if (CustomErrorHandler.isHttpErrorResponse(error)) {
            console.log(error);
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

yes, even with this my error is not getting caught... I removed the rxjs catchError from the service and I get a console log from the handler :(
yes, if you use this handler, you don't need the catchError in the service
That's a huge pain. I thought the interceptor or error handler would have the priority over this... :( Thanks Michal
I'm having the same issue. So can't the interceptor handle custom exceptions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.