Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript(or Javascript) Fetch API async/await error handling

I want to use async/awayt syntax, Fetch API and want to achieve the following behavior:

if the response is not 200, log the response, don't throw anything and return null. if the response is 200, return the response.

But! Fetch API throws an exception for everything that is different from 404, 505 or 200 and in the end I get an ugly construction like this:

...
try{
 let response = await fetch(url, {method: 'GET', mode: 'cors'});
 if(response.status != 200){
    console.log('Failed to get what I want, got status: ' + response.status);
    return null;
 }
catch(e){
  console.log('error bla bla');
  return null;
}
...

Is there a more elegant way to achieve the same?

like image 765
Anton Pilyak Avatar asked Feb 06 '26 06:02

Anton Pilyak


1 Answers

From MDN:

A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example.

And:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

As Garry said in his answer, I suggest creating a middleware to handle the non-successful responses, or just throw exceptions if the status is not 200, or the response.ok is false.

Example (using https://httpstat.us/):

async function getData() {
  try {
    let response = await fetch('https://httpstat.us/401', {
      method: 'GET',
      mode: 'cors'
    });
    if (!response.ok) throw new Error(response.statusText);
    console.log('Dataaa');

    return response
  } catch (e) {
    console.error(e);
    return null
  }
}

getData()
like image 167
Fcmam5 Avatar answered Feb 07 '26 21:02

Fcmam5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!