after reading the documentation on angular about http client error handling, I still don't understand why I don't catch a 401 error from the server with the code below:
export class interceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('this log is printed on the console!');
return next.handle(request).do(() => (err: any) => {
console.log('this log isn't');
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log('nor this one!');
}
}
});
}
}
on the console log, I also get this:
zone.js:2969 GET http://localhost:8080/test 401 ()
core.js:1449 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "http://localhost:8080/test", ok: false, …}
When the error occurs in the HTTP Request it is intercepted and invokes the catchError . Inside the catchError you can handle the error and then use throwError to throw it to the service. We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS .
What is an Angular HTTP Interceptor. The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators.
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
Your error handler needs to return a new Observable<HttpEvent<any>>()
return next.handle(request)
.pipe(catchError((err: any) => {
console.log('this log isn't');
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.log('Unauthorized');
}
}
return new Observable<HttpEvent<any>>();
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With