7
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?

Community
  • 1
  • 1
Jari Pekkala
  • 847
  • 7
  • 8
  • Have you tried looking at this: http://stackoverflow.com/questions/37052617/how-to-deal-with-http-status-codes-other-than-200-in-angular-2 ? – Matey Jan 03 '17 at 14:13
  • Yes, it returns the same ProgressEvent in the catch block too. Also worth of mentioning the Angular version: 2.2.1 – Jari Pekkala Jan 03 '17 at 14:22
  • Is it perhaps possible that the progress event is only a first of two events and the regular error event only comes after it? Or does the http call only trigger this one progress event and nothing afterwards? – Matey Jan 03 '17 at 14:26
  • Only this one response is given, nothing afterwards. The status code from the API is 422 – Jari Pekkala Jan 03 '17 at 14:28
  • That's odd. Can you provide a demo/fiddle/plunker? Have you tried testing the API in Postman? Does it behave the same way there? – Matey Jan 03 '17 at 14:32
  • http://plnkr.co/edit/gV0oeVaP0uWci2Up1KxS?p=preview – Jari Pekkala Jan 03 '17 at 14:56
  • 4
    This looks like a cross-origin issue (look for CORS). The request fails on the OPTIONS command and therefore the server probably does not even receive the request. The error is raised by client browser before sending the actual PUT request to server. – Matey Jan 03 '17 at 15:03
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132209/discussion-between-jari-pekkala-and-matey). – Jari Pekkala Jan 03 '17 at 15:06
  • @JariPekkala actually I have this same issue and would like to know what you guys found out… – Kunepro Apr 04 '17 at 11:21
  • @Kunepro it was indeed related to the API. I was using Laradock/Docker nginx container that didn't like OPTIONS sometimes – Jari Pekkala Apr 05 '17 at 16:40

2 Answers2

0

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.

SoilChang
  • 281
  • 3
  • 4
0

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),
);
Mavlarn
  • 3,807
  • 2
  • 37
  • 57