Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get body from HttpErrorResponse in Angular 6?

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 when there is no file available at the server the Response has a error code as 404 i.e Bad Request with some message in body.

But I am not able to parse that error message from body since HttpErrorResponse is giving a blob object in error.error

How do I get the actual body from the error object instead of blob.

Also is there any way to configure angular that on success of an api call parse the request in blob otherwise parse it in json ???

Hoping for a resolution

like image 813
Nitish Kumar Avatar asked Dec 13 '18 09:12

Nitish Kumar


People also ask

How do you get httpErrorResponse?

Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor.

Can we send request body in GET request in Angular?

Just to clarify some of the answers here, firstly, as stated Angular does not support supplying a body with a GET request, and there is no way around this. The reason for that is not Angular's fault but that of XMLHttpRequest (XHR), the API that browsers use for making requests.

What is httpErrorResponse in Angular?

HttpErrorResponselink A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.

What does HttpClient post return Angular?

HttpClient. post() method is an asynchronous method that performs an HTTP post request in Angular applications and returns an Observable. HttpClient. post() has a type parameter similar to the HttpClient. get() request, through which we can specify the expected type of the data from the server.


1 Answers

Try this

if(error.error instanceof Blob) {
    error.error.text().then(text => {
      let error_msg = (JSON.parse(text).message);
      console.log(error_msg)
    });
} else {
    //handle regular json error - useful if you are offline
}       
like image 113
dp_t Avatar answered Sep 18 '22 14:09

dp_t