I have a service method which makes an API post request for logging out of the application.
public logout(): Observable<APIResponse | ResponseError> {
return this.http
.post<APIResponse>(API_ENDPOINT + LOGOUT_URL, '{}', this.httpHeaders)
.pipe(catchError((error) => {
return of(this.handleError(error.error));
}));
}
The catchError catches all the other valid errors thrown from the server. However, when there's no network connection or when the server is down, it does not work.
What is interesting is the fact that, all these errors are properly caught by my interceptor which does some customised handling for specific responses.
Can anyone tell me why it is working in interceptor but not in my service? I am using the same catchError operator in my interceptor too.
Here's the inereceptor
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.endsWith('/login')) {
return next.handle(req);
}
const body = JSON.parse(<string>req.body);
const copiedReq = req.clone({ body: body });
return next.handle(copiedReq)
.pipe(tap(evt => { }), catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
const httpError: HttpErrorResponse = err;
// Custom logic ...
}
return of(err);
}));
}
If you use the same catchError in your interceptor, the behavior you describe is exactly what I would expect. In that case, the error is swallowed by your interceptor.
.pipe(catchError((error) => {
return of(this.handleError(error.error));
}));
The catchError catches any error on the Observable stream. If an error arrives in your interceptor, it is catched and a new value is emitted on the Observable stream using of.
I would recommend to use throwError instead of of in your interceptor, because then the original error is emitted back on the Observable stream and eventually will arive in your service.
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