HttpInterceptor in Angular 4.3: Intercepting 400 error responses
At the time I was trying Angular 7+.
Unfortunately above solutions did not serve the job well because
.do
is not directly available onHttpHandler
as of RxJs 6 pipes notion; and convertingObservable to Promise
does not stick.
Here is clean and up-to-date approach; I pipe
the catchError
operator and analyze the error and finally re-throw it by using throwError
. Here is final shape of interceptor;
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// client-side error or network error
} else {
// TODO: Clean up following by introducing method
if (error.status === 498) {
// TODO: Destroy local session; redirect to /login
}
if (error.status === 401) {
// TODO: Permission denied; show toast
}
}
return throwError(error);
})
);
}
Hopefully this solution will help someone in future.
Http
sends errors down the error stream of an observable so you will need to catch them with .catch
(you can read more about this here).
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event);
}
})
.catch(err => {
console.log('Caught error', err);
return Observable.throw(err);
});