Vuex axios call can't handle 422 response

I’m trying to handle 422 response from API in case data is invalid when making 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 request is successful all works fine and I get response, however if response is 422 it doesn’t fall throw exception and 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?

15 thoughts on “Vuex axios call can't handle 422 response”

  1. 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
    }
    
    Reply

Leave a Comment