Search code examples
angulartypescriptrxjshttpclient

Angular http handling json response in case of http error


I can't solve this issue and online I can't find anything, I do a post call like so:

return this.http.post(url, body, { headers: ConnectFunctions.getHeader() }).pipe(
  map(result => {
    return result;
  }),
  catchError(ConnectFunctions.handleError(url, []))
);
}

this is the response I get from the server

{"status":500,"timestamp":"21-07-2020 03:51:17","message":"my custom message","details":"some details"}

I would like to get the variable message ("my custom message") but I'm not able.

public static handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
        console.log("Error use: " + `${operation} failed: ${error.message}`);
        console.log("Error statusText: " + error.statusText);
        return of(error as T);
    };
}

How can I do it?

Thanks for your help.


Solution

  • There are some ways to catch the error, but you can summarize it:

    return this.http.post(url, body, { headers: ConnectFunctions.getHeader() })
          .catch((err: HttpErrorResponse) => {
        // simple logging, but you can do a lot more,
        console.error(err.error.message);
      });
    

    See more about HttpErrorResponse: https://angular.io/api/common/http/HttpErrorResponse