0

In the below code, if the function call() is being called with await, then my console is not logging the "finished" value. So this basically means that due to the uncaught error, the function is being stopped right at the await line and the error handling code should come into place.

    function call()
      {
        return Promise.reject("done")
      }
    
      React.useEffect(()=>{
        async function check(){
          const x = await call();
          console.log(x);
          console.log("finished");
        };
        check();
      },[])

However, if I'm using fetch() then even with an error, the below lines are being executed and console logged.


    React.useEffect(()=>{
        async function check(){
          const x = await fetch("https://www.thecocktaildb.com/api/json/v1/1/");
          console.log(x);
          console.log("finished");
        };
        check();
      },[])

Why is there a different behavior for fetch errors and function call errors?

  • 1
    *"even with an error"* - What error is `fetch` producing? Is it rejecting the promise, or is there just an HTTP error code? How have you confirmed and observed that it is **specifically** rejecting the promise? (Such as by wrapping it in a try/catch) – David May 15 '23 at 14:54
  • Does this answer your question? [Fetch: reject promise and catch the error if status is not OK?](https://stackoverflow.com/questions/38235715/fetch-reject-promise-and-catch-the-error-if-status-is-not-ok) – David May 15 '23 at 15:01
  • Your `call()` function would typically be declared async. – jarmod May 15 '23 at 15:05
  • If it returns a `Promise.reject`, then no, it wouldn’t. – user3840170 May 15 '23 at 15:20

1 Answers1

2

The difference in behavior between the two is due to the fact that the fetch() method does not reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it resolves normally (with ok status set to false), and it only rejects on network failure or if anything prevented the request from completing.

On the other hand, when you use await with a function call that returns a rejected promise, it will throw an error and stop executing the function. This is why you are not seeing the “finished” value being logged.

To handle errors with fetch(), you can check if the response is ok and throw an error if it’s not. Here’s an example:

async function check() {
    const response = await fetch("https://www.thecocktaildb.com/api/json/v1/1/");
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
    console.log("finished");
};
check();
Ganael D
  • 77
  • 4