Handle a 500 response with the fetch api
Asked Answered
E

2

47

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?

Endeavor answered 25/3, 2016 at 18:35 Comment(2)
i'm not familiar at all with the framework or the fetch api, but i found this: gist.github.com/bryanrsmith/14caed2015b9c54e70c3; fetch().then().catch(unk => conole.log(unk));Lilith
Nice research. That is also shown here: developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Thank you.Endeavor
E
73

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

Endeavor answered 25/3, 2016 at 19:2 Comment(0)
S
0

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

Sarajane answered 13/1, 2023 at 7:22 Comment(1)
this doesnt do anything, since the .then() is never reached. you need to wrap it inside a .catch() to get whatever response you have..Fari

© 2022 - 2024 — McMap. All rights reserved.