简体   繁体   中英

VueJS, Axios, Laravel - catch errors

I am using the following code to post something to Laravel:

        upload: async function() {     

        response = await axios.post(url, data, {
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        }).catch(function(error) {
            console.log(error.response.data.errors);
        });

(Unrelated code omited)

This works overall when Laravel returns 200. If I return 401, 422 or something from Laravel Axios throws an error in the console and the whole method stops running.

I've always considered this a very non-developer-friendly behavior - am I not understanding it? Returning different status codes from your backend API is supposed to help reading the response in Vue, but Vue/Axios treat every non-200 response as a fatal error.

How can I catch the error - do something (and bind $this to the callback) and then continue with the method without killing the whole script?

The reason is that Axios default has a validator function like this:

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

Status codes 300 and above and less than 200 will make axios throw.

You can make it not throw (stop the further execution) by either:

try..catch:

try {
    response = await axios.post(url, data, {
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    });
} catch (error) {
    this.doSomething() // this is available here
}

.catch on axios:

axios.post(url, data, {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
}).catch(error => {
    console.log(error.response.data.errors);
});

NOTE: This is different to your example due to not using async/await

Error callback:

axios.post(url, data, {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
}, error => {
    console.log(error.response.data.errors);
})

If you do not want Axios to force you that status codes above 300 will throw, you can make change the default axios validator:

axios.defaults.validateStatus = (status) => {
    return status === 200; // your own logic here to throw or not.
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM