How to get body from HttpErrorResponse in Angular 6?

后端 未结 5 817
予麋鹿
予麋鹿 2020-12-11 17:14

I have created a REST API call in my Angular app which downloads a file.

I am setting responseType to \'blob\' since I am expecting a file in response.

But w

5条回答
  •  爱一瞬间的悲伤
    2020-12-11 17:41

    For future visitors (since the title is generic):

    If the backend returns JSON upon error (ideally, following RFC 7807, which would also mean application/problem+json content-type too), the error.error is a JSON object, not a string. So to print it, for example, you would need to stringify it first:

    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${JSON.stringify(error.error)}`);
    

    I believe the confusion starts from the official Angular documentation, which contains this statement:

    // 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}`);
    

    But with error.error being a JSON object (in the standard cases), you get printed [object Object] for the body instead of the string representation of that JSON object. Same unhelpful output if you try ${error.error.toString()}.

提交回复
热议问题