Using validateStatus in Axios

This past week I was working with an API endpoint where a 404 response is expected for invalid user input. I didn’t want Axios to treat this as an error. It had been awhile since I last needed to do this, but reading through the request configuration docs I was reminded of validateStatus. By default, it will return true for all 2xx responses.

validateStatus: (status) => {
  return status >= 200 && status < 300; // default
},

In this case, I want the promise to resolve for 404 responses as well.

validateStatus: (status) => {
  return (status >= 200 && status < 300) || status == 404;
},

And that’s it. When the user puts in invalid input, the promise will still resolve. This isn’t something you often want to do, but it’s good to keep in mind depending on what a 404 actually means for your use case.

2 thoughts on “Using validateStatus in Axios

  1. zzynx

    > By default, it will return true for all 2xx and 3xx responses
    Given the code for the default:
    return status >= 200 && status < 300; // default
    I think that should read:
    will return true for all 2xx responses.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s