Reputation: 51638
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.
Upvotes: 3
Views: 2048
Reputation: 214017
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
}));
}
Upvotes: 4