Unhandled Promise Rejection: AxiosError: Network Error

Viewed 35

Working on a MERN stack project. When trying to access the site on localhost on iPhone Posts are posts are not loading. Working fine on adnroid devices. Screenshot of error

const fetchFeedPosts = async () => {
    const URL = `${BASE__URL}api/posts/feed/${LOGGED__IN__USER}`;
    await axios.get(URL)
    .then((response) => setFeedPosts([...response.data].reverse()))
    .catch((e) => console.log(e.response));
}
fetchFeedPosts()
1 Answers

What the error means

When an Error is thrown (e.g. throw new Error()) it can

  • be catched locally (e.g. try{...} catch(err) { /** here */ })
  • or be passed on to the calling function. And in that fashion it bubbles up from caller to caller until it reaches a catch somewhere.

However, if it continues to bubble up, and there's nothing that captures it by the time it reaches the root of your application or code, then that will result in a so-called "Unhandled" error.

Now, as you may know, promises are more like jobs that drift around. They aren't called from the root of your application. But as they bubble up they can also reach a similar root-point, in which case they become "Unhandled Promise rejections".

What to do about it

Unhandled errors or rejections are bad practice though. Errors should be caught somewhere. And without catching them, you can't really know what has caused the error to happen in the first place.

In most cases, you can catch them with a .catch() function, (e.g. yourPromise.catch((err) => {console.err(err)}))

In case your promise is handled in an async function and waited for with an await keyword, then it's slightly different. In that case it makes more sense to use a try-catch block to capture your error.

How to apply it to your code

So, the first way of doing it would be to use the .catch() function

axios.get(URL)
  .then((response) => setFeedPosts([...response.data].reverse()))
  .catch((err) => console.error(err));

The alternative is to use the await syntax with a try-catch. If you want to use this syntax, you have to put the async keyword before your function.

try {
  const response = await axios.get(URL)
  setFeedPosts([...response.data].reverse()))
} catch (err) {
  console.log(err);
}

Sure, you could mix the 2, but in most cases that would be rather strange.

Related