Vuex axios call can't handle 422 response
Asked Answered
P

1

2

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?

Prankster answered 19/2, 2021 at 21:41 Comment(0)
L
5

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
}
Levins answered 19/2, 2021 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.