Search code examples
angular5angular-httpclient-interceptors

Angular 5 - Manipulating HttpErrorResponse's error property in HttpInterceptor


I have custom error message body as JSON from rest api.

{  
   "status":400,
   "url":"/api/abc",
   "message":"Custom Error Message"
}

I want to get it as object in subscribe's error scope. I tried to convert it to an object after every response using HttpInterceptor. But HttpErrorResponse is read-only. How can I obtain this object in service?

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).do((event: HttpEvent<any>) => {}, (err: any) => {
            if (err instanceof HttpErrorResponse) {
                // Here trying convert to object from json
                err.error = <ErrorMessageBody>JSON.parse(err.error);
            }
        });
    }

Solution

  • err.error is already translated to JSON.

    This worked for me with catch:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch((err: HttpErrorResponse) => {
                return Observable.throw(err.error);
            });
    }