PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Written By

Error handling in Fetch VS Axios

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

then, we can handle the result with;

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

return data; // Do something with your data

Conclusion

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

Cover Photo by Markus Spiske on Unsplash

Comments (0)

loading comments