Can I throw error in axios post based on response status

If you give a look at the GitHub Project Page you will notice following option description.

/* `validateStatus` defines whether to resolve or reject the promise for a given
 * HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
 * or `undefined`), the promise will be resolved; otherwise, the promise will be
 */ rejected.
validateStatus: function (status) {

    return status >= 200 && status < 300; // default
},

So you could create an Instance with your own configuration.

var instance = axios.create({

   validateStatus: function (status) {

        return status == 200;
    },
});

You could also set defaults. These will be applied to every request.

axios.defaults.validateStatus = () => {

    return status == 200;
};

UPDATE 1

To set the config only on a specific operation you could replace “config” with your desired values or methods.

axios.post(url[, data[, config]])

UPDATE 2

I tried this, but it didn’t work.

You cannot pass the instance to axios.post(). You must call post on the new instance.

var instance = axios.create({

    validateStatus: function (status) {
        return status == 200;
    }
});

instance.post('url', data, config);

Leave a Comment