Angular2 http response body on error

6.2k Views Asked by At
this.http.put(url, data)
    .map(response => response.json())
    .subscribe(
      response => console.log(response),
      error => console.log(error),
    );

On success it outputs the data returned from the API. On error the output is ProgressEvent with status of 0.

How to get the response data from the API when error occurs?

2

There are 2 best solutions below

0
On

You can check the _body property in response, like:

this.http.put(url, data)
.map(response => {
  if (response['_body']) { // check response here.
    return response.json()
  } else {
    return {} // or return null.
  }
})
.subscribe(
  response => console.log(response),
  error => console.log(error),
);
0
On

You can probably try

this.yourHttpCall().subscribe(
        val => {
            //do something
        },
        err => {
            let error = (() => { try { return JSON.parse(err._body) } catch (something) { return err })()
            console.log(error);
        }

    );

That's kind of a hack around it. Not sure if it works for your endpoint.