0
votes

I am using HttpClient to create a POST request and return Observable to the caller. When a caller subscribes and tries to catch an error, the error is a string instead of the expected HttpErrorResponse as usually seen in the documetation. screenshot of developer console

I have tried to handle error directly in the calling method using a pipe with a catchError, but it receives the same error as the one above.

Here is the code of my service method

createPartner(partner: Partner) {
    return this.http.post(this.publicUrl + "partner", partner).pipe(catchError(this.handleError));
  }

 handleError(error: HttpErrorResponse) {
    console.log(error);
    return throwError(error);
  }
3

3 Answers

3
votes

I have found the problem, I have forgotten that I have an interceptor that was changing the error. If anyone else is as forgetful as I am, check your interceptors!

0
votes
 /** Error Handling method */

  handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');

  }
0
votes

You might check the documentation again, as the error message is listed in the docs to be of type string. https://angular.io/api/common/http/HttpErrorResponse#constructor(). Also notice the server is kicking back a status 500, you might consider https://angular.io/api/common/http/HttpInterceptor too.