August
August

Reputation: 1819

Fetch still throws despite having catch block

fetch('https://api.postcodes.io/postcodes/aassdd')
  .then((resp) => {
    console.log(resp.status);
  })
  .catch((e) => { console.log('ha'); });

For some odd reason the code above will still throw error and execute the .then statement afterwards. Is there a way to fix this ?

Edit: fiddle

Upvotes: 0

Views: 936

Answers (1)

Alexander O'Mara
Alexander O'Mara

Reputation: 60507

Most browser developer consoles normally logs 404 errors by default, and some may, or can be configured to, log all requests.

Console screenshot

The fact that you see see an error here doesn't mean a catch-able JavaScript exception was thrown, in addition to JavaScript console logs and throw exceptions, the browser console also shows other things.

There isn't anything you can do in your code to stop this error from appearing in the console, but some consoles would let you hide those requests from the console.

Also, fetch does not throw an error on typical error response codes like 404. This is to make it more-flexible, and let you decide if you still want the content, even if it is a 404 response code.

If you want to throw an error on a non-200 status code, you could do this:

fetch('https://api.postcodes.io/postcodes/aassdd')
  .then((resp) => {
    if (resp.status !== 200) {
        throw new Error('Invalid status code: ' + resp.status);
    }
  })
  .catch((e) => { console.log('ha'); });

Upvotes: 1

Related Questions