Reputation: 4360
I want to intercept each request and error responses.
I already can intercept requests and set a token in the headers and I can intercept the responses to handle a refresh token.
However I can't find a way to intercept HttpErrorResponse
.
I tried 2 methods. One with an explicit rxjs catchError and the other with some kind of callback:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = this.auth.getToken();
if (authToken) {
req = req.clone({ headers: req.headers.set('accesstoken', authToken) });
}
return next.handle(req).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
//handle refresh token
}
return event;
},
catchError((error: any) => {
if (error instanceof HttpErrorResponse) {
console.log(error);
return Observable.throw(error);
}
})));
}
If I have an expired token, every request throws an HttpErrorResponse but this solution doesn't catch it.
This is returned by the service. No sign of the console.log() from the interceptor.
The service looks like this:
public getData(): Observable<any> {
return this.http
.get<any>(url)
.pipe(
map(res => {
return res;
}),
catchError((e): Observable<any> => {
console.log(e);
const res: any = {error: e};
return of(res);
})
);
}
Then I tried with a "callback syntax":
return next.handle(req).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// refresh token
}
return event;
}, (error: any) => {
if (error instanceof HttpErrorResponse) {
console.log(error);
}
}));
Same result as above. Nothing in the console.
I've seen people (https://medium.com/@aleixsuau/error-handling-angular-859d529fa53a) register an ErrorHandler in the module but I haven't tried it yet.
How do I catch an HttpErrorResponse from my interceptor?
EDIT:
I've tried the ErrorHandler way but still couldn't get any log. Then I removed the catchError
from my service and finally got something logged...
I'll try to see if this makes the interceptor work... Not fun if I have to remove all my catchError :(
I made a reproducible example here: https://stackblitz.com/edit/angular-m2jc9n
Upvotes: 1
Views: 1137
Reputation: 131
Angular has a hook for error handling (https://angular.io/api/core/ErrorHandler).
You can create a service which implements the angular ErrorHandler and implements handleError
method where you can log all errors. This error handler would log not just HttpErrorResponse but all errors, but you can filter out the ones you need.
@Injectable()
export class CustomErrorHandler implements ErrorHandler {
private static isHttpErrorResponse(error): error is HttpErrorResponse {
return error instanceof HttpErrorResponse;
}
handleError(error: any): void {
if (CustomErrorHandler.isHttpErrorResponse(error)) {
console.log(error);
}
}
}
Upvotes: 4