Get net::ERR from failed fetch in a try catch, it's not in the caught error

443 views Asked by At

I am expecting an error, and don't need help preventing it. I want to handle it better.

I'm wrapping a fetch from isomorphic-fetch with a try catch,

let response;
try {
  response = await fetch(getFoosFromFooville(), { method: 'GET'})
} catch (error) {
  // TODO handle error; for not just print it
  console.log(error)
}

And in the dev console I see an error like:

GET https://example.com/foos/fooville net::ERR_SOMETHING_RELEVANT_TO_FOOS

That's not from my catch block. The console.log statement in the catch block just prints:

TypeError: Failed to fetch
  at Object.fooFetch (fooFetching.js?beef:42)
  at ...

It's much more useful if I could get the net::ERR_SOMETHING_RELEVANT and handle that.

Is that something I can do, or is it the library or native javascript it polyfills?

1

There are 1 answers

1
Caleb On

Try this:

fetch(getFoosFromFooville(), { method: 'GET'})
  .then((response)=>
    console.log(response)
  })
  .catch((error)=>{
    console.log(error)
  })

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch