I am having a difficulty in detecting the error status code and error message in Angular error interceptor:
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private loading: LoadingService,
private msg: ShowMessageService
) { }
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err: any) => {
// eslint-disable-next-line no-console
console.error("Error occured while calling BE API: ", err);
this.loading.setLoading(false);
let errorMsg = err.error.message;
if (err.error.message !== undefined) {
errorMsg = err.error.message;
} else if (err.error.ErrorMessage !== undefined) {
errorMsg = err.error.ErrorMessage;
} else {
switch (err.status) {
case 0:
errorMsg = "Sorry for inconvenience. An error occurred during communication with the server.";
break;
case 401:
errorMsg = "Sorry for inconvenience, but you are not authorized for this.";
break;
//more http codes added here to handle, 404, 500, etc.
default:
errorMsg = "Sorry for inconvenience, but an error occurred during communication with the server. Please contact the administrator.";
}
}
this.msg.showErrorMsg(errorMsg);
return of(err);
})
);
}
}
When I use Postman, I get the following error message from backend:
{
"error": {
"code": 500,
"message": "Fail to handle the request."
}
}
But in Angular, I can't get this error message, although in Chrome dev tools, I can see the status is 500, and polyfills.js print error as net::ERR_FAILED 500 (Internal Server Error):
But there's no response. Here's the screenshot of response (Failed to load response data):
And when I print the error in console, I always get error code 0, for failed requests. Does Angular interceptor override the HTTP error messages from backend? What should I do to prevent this?

