44

We have the following call to fetch.

this.http.fetch('flasher', { method: 'post', body: jsonPayload })
    .then(response => response.json())
    .then(data => console.log(data));

This works when we receive a 200 response but logs nothing to the console when we receive a 500 response. How do we handle a 500?

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • 3
    i'm not familiar at all with the framework or the fetch api, but i found this: https://gist.github.com/bryanrsmith/14caed2015b9c54e70c3; fetch().then().catch(unk => conole.log(unk)); – AndreaBogazzi Mar 25 '16 at 18:41
  • 2
    Nice research. That is also shown here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Thank you. – Shaun Luttin Mar 25 '16 at 18:43

2 Answers2

67

Working Solution

Combining then with catch works.

fetch('http://some-site.com/api/some.json')  
  .then(function(response) {                      // first then()
      if(response.ok)
      {
        return response.text();         
      }

      throw new Error('Something went wrong.');
  })  
  .then(function(text) {                          // second then()
    console.log('Request successful', text);  
  })  
  .catch(function(error) {                        // catch
    console.log('Request failed', error);
  });

Details

fetch() returns a Promise containing a Response object. The Promise can become either fulfilled or rejected. Fulfillment runs the first then(), returns its promise, and runs the second then(). Rejection throws on the first then() and jumps to the catch().

References

MDN - Promise

MDN - Checking that the fetch was successful

Google - Introduction to Fetch

Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • 8
    This is probably not going to do what you want. This will either result in a false positive (if the server returns a textual error response on a 4xx-5xx status) or extracting text will fail and it will log the error of the call to `response.text()`, which will most likely be unhelpful. You should instead check the status code or `res.ok` explicitly in the first `then` and respond accordingly. See [here](https://www.tjvantoll.com/2015/09/13/fetch-and-errors/). – neverfox Feb 21 '17 at 23:26
  • @neverfox Thank you for that. Updated. – Shaun Luttin Feb 22 '17 at 15:28
0

Just try to wrap in an object like console.log({data})

Fedor
  • 17,146
  • 13
  • 40
  • 131
allweek
  • 41
  • 4