skip to Main Content

I’m implementing an asynchronous function to fetch and show JSON data from an API.

In order to handle errors properly, I’m using a try/catch block.

But I’m getting an "Uncaught (in promise)" Error – and I don’t understand why.

This is my code:

const getData = async() => {
  const url = "https://dummyjson.com/quotees?limit=20"; // it contains a typo (quotees) intentionally
  try {
    const res = await fetch(url);
    return res.ok ? res.json() : Promise.reject(res.status);
  } catch(err) {
    console.log(err);
  }
};

getData()
  .then(d => {
    if (d) d.quotes.forEach(q => ...);
  });

The output of console.log(err) is "Uncaught (in promise) 404".

Why isn’t it simply "404"?

2

Answers


  1. You return a rejected promise which is unhandled thus raising an error at the global scope. To use your catch block just throw:

    const getData = async() => {
      const url = "https://dummyjson.com/quotees?limit=20"; // it contains a typo (quotees) intentionally
      try {
        const res = await fetch(url);
        if(res.ok) return res.json();
        throw res;
      } catch(err) {
        if(err instanceof Response){
          console.log('response error:', err.status);
        } else {
          console.log('another error:', err);
        }
      }
    };
    
    getData();
    Login or Signup to reply.
  2. I think you can throw the rejected promise and add a catch block to handle it.
    Something like the following should work –

    const getData = async() => {
      const url = "https://dummyjson.com/quotees?limit=20"; 
      try {
        const res = await fetch(url);
        if (!res.ok) {
          throw new Error(res.status);  
        }
        return res.json();
      } catch(err) {
        console.log(err);  
    };
    
    getData()
      .then(d => {
        if (d) d.quotes.forEach(q => ...);
      })
      .catch(err => {
        // error handling
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search