8

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?

7
  • Where's the async declaration? May 24, 2019 at 15:32
  • well, it is all inside an async function, yes May 24, 2019 at 15:33
  • Fetch API throws an exception for everything that is different from 404, 505 or 200 -- Fetch is only supposed to reject for network errors not based on status code.
    – Mark
    May 24, 2019 at 15:34
  • @Mark: but when the server returns 400, is it considered as a network error? I have an unhanded exception in this case and want to avoid it. May 24, 2019 at 15:37
  • If you just try to make a simple and pretty architecture you may want to create a wrapper around fetch to handle cases like this, i mean make your own fetch with blackjack and desired error handling. Also mention this - stackoverflow.com/questions/50330795
    – lucifer63
    May 24, 2019 at 15:40

4 Answers 4

10

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 response.statusText;
    console.log('Dataaa');

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

getData()

1
  • You also could use throw new Error(`${resp.statusText} ${await resp.text()}`) for additional information about the error.
    – hayesgm
    Feb 21 at 5:33
2

Fetch does not throw based on status code. It will throw if there's a network error such as not being able to reach the server. This is defined in the Fetch spec.

Here's an example of getting various status codes from Fetch

async function getit(status) {
  let url = 'https://httpstat.us/' + status
  try {
    let response = await fetch(url, {
      method: 'GET',
      mode: 'cors'
    });
    if (response.ok) {
      console.log("Got what we wanted")
    } else {
      console.log('Failed to get what I want, got status: ' + response.status);
    }
    return "okay";

  } catch (e) {
    console.log('A real error!');
    return "network error";
  }
}

getit(200).then(console.log)

// error codes
getit(400).then(console.log)
getit(503).then(console.log)
getit(401).then(console.log)

So long as it receives an HTTP response, it should not throw.

(You do have a typo in your code — you're missing the closing bracket on the if (response.status != 200) {, but this should cause a syntax error not a rejected promise)

2

I would say create a middle ware and call that middleware function like fetch().then(middleware). This way it will always go to middleware method for every request and you can add your check in one place.

3
  • Great idea, but wouldn't it be more convenient to create some helper class on top of fetch?
    – lucifer63
    May 24, 2019 at 15:37
  • yes, of course, I can create a class on top of Fetch, but it seems like a very trivial problem, is there a more clean solution for that? May 24, 2019 at 15:38
  • I am using the similar concept. I have two three different middlewares and using it accordingly. If you do not want to add any middleware or helper class on top of fetch then you can add check on every request (the way you are doing ) and proceed it. But in my opinion creating middleware/helper class would be cleanest and reusable.
    – Garry
    May 24, 2019 at 16:02
1

If you're open to using an alternative to fetch(), axios seems to have cleaner/configurable error handling. In fact, the default settings match your use case perfectly. (Reject if anything other than status code 2XX):

try {
    let response = await axios.get(url, {mode: 'cors'});
    return response;
} catch (error) {
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log('Failed to get what I want, got status: ' + error.response.status);
    } else {
        console.log('error bla bla');
    }    
    return null;  
}

(BTW getting JSON with axios is just a single step vs. two steps for r = await fetch(), then r.json())

1
  • 1
    Why use an external library, when we have a native one? (even polyfills for the old browsers) Feb 12, 2020 at 4:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.