Jari Pekkala
Jari Pekkala

Reputation: 888

Angular2 http response body on error

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?

Upvotes: 7

Views: 6298

Answers (2)

Mavlarn
Mavlarn

Reputation: 3883

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),
);

Upvotes: 0

SoilChang
SoilChang

Reputation: 351

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.

Upvotes: 0

Related Questions