DEV Community

loading...
Cover image for Error handling in Fetch vs Axios

Error handling in Fetch vs Axios

bugs_bunny profile image Derek Oware ・2 min read

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);

then, we can handle the result with;

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

return data;

In this case, if we have something like

if (data) {
  // Do something
}

somewhere in our code, we get the expected result.

Conclusion

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

Cover Photo by Markus Spiske on Unsplash

Discussion

pic
Editor guide