gpt4 book ai didi

vue.js - Vue,使用axios调用时如何处理错误

转载 作者:行者123 更新时间:2023-12-03 08:06:35 25 4
gpt4 key购买 nike

我正在尝试研究使用axios时如何处理错误。请参见下面的代码:

//Admin.vue

methods: {
saveClicked: function(){

updateConfig(this.editedConfig)
.then(response => {
console.log("in here");
console.log(response);
this.info.showAlert = true;
this.info.message = "Successfully updated config!!"
this.info.alertType = "success";
this.showJsonEditor = !this.showJsonEditor;

})
.catch(error => {
this.info.showAlert = true;
this.info.message = "Failed to update config, please try again later"
this.info.alertType = "error";
});
}
}

//network.js

function updateConfig(editedConfig){

return axios.put(URL,editedConfig, {
headers: {
"Content-type": "application/json"
}
})
.then(response => response)
.catch(error => error);
}

请求成功后,一切都很好。我收到警报说一切都很好。

我强制后端为每个请求返回错误,因此我可以在Vue应用程序中模拟错误行为,这就是我观察到的结果:

即使收到错误。该程序正在通过 then()中的 Admin.vue检查以下图片:

enter image description here

我错过了什么?

最佳答案

问题:您为什么添加:

   .then(response => response)
.catch(error => error);

在您的 network.js文件中?

我想您对Promise有一些误解。

从API Promise.prototype.then 将返回另一个 promise 。这个 新的 Promise可以用作成功完成某件事或捕获异常的一种方式。

从API Promise.prototype.catch 将返回另一个 promise 。这个 新的 promise 有些不同。从文档中:

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.



因此,在您的情况下,它将在下一个 resolve调用中调用 then。除非您在 network.js文件中抛出错误是没有意义的。

删除 network.js文件中的第2行,您将获得预期的行为。

关于vue.js - Vue,使用axios调用时如何处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com