如何解决如何避免Promise中的重复捕获功能
最近,我在VueJS中与Promises一起工作。我必须在项目中多次重复catch
函数。如何在代码中的单个位置处理错误?
saveLocation(_,data) {
const self = this._vm.$nuxt;
self.$api.Store.Add_Location(data)
.then(() => {
self.$notification("success",self.$t("message.actionSuccess"));
self.$router.push(PUSH_BACK_URL);
})
.catch(self.$commitError);
},z
updateLocation(_,{ payload,push }) {
const self = this._vm.$nuxt;
self.$api.Store.Update_Location(payload)
.then(() => {
self.$notification("success",self.$t("message.actionSuccess"));
if (push) self.$router.push(PUSH_BACK_URL);
})
.catch(self.$commitError);
},destroyLocation(_,push }) {
const self = this._vm.$nuxt;
self.$api.Store.Delete_Location(payload)
.then(() => {
self.$notification("success",self.$t("location.deleteSuccessMessage"));
if (push) self.$router.push(PUSH_BACK_URL);
})
.catch(self.$commitError);
},
解决方法
您可以跳过为每个promise编写catch块并在此全局promise catch处理程序中捕获错误
window.addEventListener('unhandledrejection',function(event) {
alert(event.promise); // [object Promise] - the promise that generated the error
alert(event.reason); // Error: Whoops! - the unhandled error object
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。