Reputation: 11
Recently I work many with Promises in VueJS. I have to repeat the catch
function many times in my project. How can I handle the error at single place in the code?
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(_, { payload, 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);
},
Upvotes: 1
Views: 64
Reputation: 488
You can skip writing the catch block for every promise & catch the error inside this global promise catch handler
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
});
Upvotes: 1