1

When I make a request to a Node server from the client using whatwg-fetch and I get a non 200 response, I'd like to be able to catch that error and return a custom response.

For example:

const makeRequest = (endpoint) => {
    try {
        return fetch(`/api${endpoint}`, requestConfig)
            .catch(e => console.warn(e))
            .then(res => res.json())
            .catch(e => console.warn(e))
    } catch(e) {
        // Never logs...
        console.warn(e);
    }
}

When I get a 502 or 404, for example, I'm still get a console.error in the console...

enter image description here

In Chrome console when I click to view the source of the error: enter image description here

I don't understand why, if fetch() caused the error, why wrapping it in a try/catch doesn't catch this error?

How can I catch the errors from fetch() for a non-200 response?

Himmel
  • 3,629
  • 6
  • 40
  • 77
  • 1
    You cannot use `try/catch` block to handle exceptions thrown asynchronously. Read more about this http://stackoverflow.com/questions/24977516/catching-errors-in-javascript-promises-with-a-first-level-try-catch – Mirceac21 Jan 13 '17 at 00:29
  • There's no error (in the meaning of "exception") in your console. It's just the default logging that a network request failed. – Bergi Jan 13 '17 at 00:33
  • @Mirceac21that's what `catch()` blocks are for, to catch rejected promises throw asynchronously. The link you posted confirms this. I have several `catch()` blocks above but it still isn't working – Himmel Jan 13 '17 at 01:25

0 Answers0