Search code examples
angularangular-http-interceptorscustom-error-handling

error handler is getting called twice angular http_interceptor


in my angular application I have a global error handler which handles all the error. also, I have http interceptor where I am trying to log the error when it happens. but, the http interceptor requires to return the observable when it catches error, right now I am throwing the error so internally its triggering the global error handler makes the error handler getting called twice. I can remove the error handler from the http interceptor and let the global error handler does the job but I will not get the correlation ID of the request to stitch the entire requests. I am having two questions, when an error happens is there a way we can access request headers (so that I can get the correleation ID) or instead or throwing the error again is there anything else I can do?

here is the current interceptor.

catchError((error: HttpErrorResponse) => {
        this.logger.logError(
          error
          nextReq.headers.get('x-correlation-id') ?? ''
        );
        return throwError(error);

Solution

  • I have added a check in the global error handler, that will only call the logger when its not an instance of HTTPError.

    if (error instanceof HttpErrorResponse) {
          // HTTP errors will be handled in interceptor itself.
        } else {
          this.logger.logException(error);
        }