简体   繁体   English

VueJS、Axios、Laravel - 捕获错误

[英]VueJS, Axios, Laravel - catch errors

I am using the following code to post something to Laravel:我正在使用以下代码向 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.当 Laravel 返回 200 时,这总体上有效。如果我从 Laravel 返回 401、422 或其他内容 Axios 在控制台中引发错误并且整个方法停止运行。

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.从后端返回不同的状态代码 API 应该有助于读取 Vue 中的响应,但 Vue/Axios 将每个非 200 响应视为致命错误。

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?我怎样才能捕捉到错误 - 做一些事情(并将$this绑定到回调)然后继续使用该方法而不杀死整个脚本?

The reason is that Axios default has a validator function like this:原因是 Axios 默认有一个验证器 function 像这样:

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

Status codes 300 and above and less than 200 will make axios throw.状态码 300 及以上且小于 200 将使 axios 抛出。

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: .catch 上 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注意:由于不使用 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 强制您抛出 300 以上的状态码,您可以更改默认的 axios 验证器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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