3

I want to treat certain HTTP error codes as non-errors, and handle their responses normally. So I tried adding an HttpInterceptor to catch 500 status codes, and return the original response (which Angular puts in error.error):

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 500) {
          return of(error.error);
        } else {
          return throwError('server error');
        }
      })
    );
  }

But then if there's an error, anything that I had piped to my http request doesn't get executed. For example, if I do this, the log statement doesn't happen:

this.http.get(...).pipe(
  tap(console.log)
)

How can I make this work?

Here's a sample...it never logs "got result" from AppComponent.

3
  • You can use tap({ next: console.log, error: console.log }) if you want to log also errors. Commented Apr 17, 2020 at 15:50
  • you're saying in the case of the 500 response, the tap isn't executing? or in non 500 responses? or both? I'd expect tap to get skipped in the case of non 500 errors, but should execute in the 500 case Commented Apr 17, 2020 at 15:51
  • @bryan60 Right, it’s not executing even for 500 errors. Commented Apr 17, 2020 at 15:56

1 Answer 1

4

Your chain stops working since Angular http module filters messages that it receives from interceptor:

const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe(
        filter((event: HttpEvent<any>) => event instanceof HttpResponse));

As you can see you should return stream of HttpResponse class like:

import { HttpResponse, ... } from '@angular/common/http';
...

if (error.status === 404) {
  console.log('caught', error.error);

  return of(new HttpResponse({
    body: error.error
  }));
}

Forked Stackblitz

Sign up to request clarification or add additional context in comments.

3 Comments

Oh my god....I could have spent a week on this and never figured that out. Thank you!
Consider to return just new HttpResponse({ body: error.error }) (not the observable). Error handler within the http interceptor should return an error or response object.
To clarify my point, you can use the 'of' method to make a observable, but if your error handler function defined with an async keyword, use return with a plain object.

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.