I'm trying to handle 422 response from my API in case data is invalid when making an async Axios call.
In a component, I have a method like:
async saveChanges() {
this.isSaving = true;
await this.$store.dispatch('updateSettings', this.formData);
this.isSaving = false;
}
And in my actions like this:
let response;
try {
response = await axios.put('/api/settings', settings);
console.log(response);
} catch (e) {
console.log('error');
console.log(e);
}
If the request is successful, everything works fine, and I get a response. However, if the response status code is 422, it doesn't fail or throw an exception, and the response is empty. I've tried with .then(()).catch(())
, but no luck either as I need it to be async.
Any suggestions what I might be doing wrong?
By default, Axios only throws an error for HTTP status codes between 200 and 300.
Either configure Axios to also throw for 422 by setting validateStatus
:
axios.put('/api/settings', settings, {
validateStatus: status => status >= 200 && status < 300 || status === 422
})
Or check the status code in your normal callback:
response = await axios.put('/api/settings', settings);
if (response.status === 422) {
// throw error
}