DEV Community

Cover image for Error handling in Fetch vs Axios
Derek Oware
Derek Oware

Posted on • Updated on

Error handling in Fetch vs Axios

There's so much difference between Fetch and Axios but my focus is on error handling because it caught my attention in my previous project.

Error handling is an essential part of every application we build thus needs to be done correctly.

From the fetch documentation on the difference between Fetch and JQuery, it shows how fetch handles errors differently but I don't think everyone knows about that because tutorials don't talk about that.

The issue

I think there's a good reason to why Fetch handles request failures the way it does but most devs including me usually forget to handle the result.
From the docs :

"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."

But this may be a problem is some case because in forms for instance, when the wrong data is sent to the server, we expect the attempt to fail. We may have a validation function and inside that function, if there's a success response we'd redirect the user or store the data.

The solution

In Axios, if there's request failure, it throws an error and you can easily handle the error with a try-catch block and get the error data from error.response.data.

In Fetch, if we have;

const res = await fetch(api);
const data = await res.json();
Enter fullscreen mode Exit fullscreen mode

then, we can handle the result with;

if (!res.ok) {
  error = data;
  return null;
}

return data; // Do something with data if successful
Enter fullscreen mode Exit fullscreen mode

Conclusion

You can check an example code on my gist or on codepen illustrating the error handling in both Fetch and Axios

Cover Photo by Markus Spiske on Unsplash

Top comments (1)

Collapse
 
khimaira profile image
Khimaira • Edited

I rather do this:

try {
    const result = await fetch(url);
    if (!result.ok) {
      throw new Error(
        `There was an Error: ${result.status} ${result.statusText}`
      );
    }

    const data = await result.json();
  } catch (error) {
    console.log(error);
  }
Enter fullscreen mode Exit fullscreen mode