Skip to main content

Command Palette

Search for a command to run...

How to suppress Axios throwing an error when it encounters a 4xx error code

Updated
1 min read

One fine day, I was told to write a script that would make multiple API calls, to add dummy data to our db.

I am a bit new to JS, I used to work with a Python stack at my previous org.

But I am a polyglot, so I don't really care what language I code in, the fundamentals are the same.

So I wrote a script, I adjusted the edge case where I received a 4xx error code. When I'd receive a 4xx error code I'd just log it and move forward with bombarding the backend with API calls.

But when I tried testing the script, Axios started throwing the 4xx error instead of logging it and moving forward. So I searched for a solution, and I found it. Here it is:

axios.post('/bird/sparrow', body , {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
});

The above will only throw an error if error code is greater than 500.

Adding validateStatus solves the problem, so now you can decide what HTTP error codes should throw an error.

Useful, right?

There are also other methods on how to do that, using .then might also work, but this better and in-built functionality so why reinvent the wheel?

Ciao

More from this blog

Vivek's Tryst with Tech

35 posts

builder of APIs, reducer of latencies, optimiser of code, fixer of issues

Backend Engineer | On my way to become 10x engineer