1

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);
    },

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Duy Kieu
  • 11
  • 1
  • This *might* be a duplicate to this question: https://stackoverflow.com/questions/52071212/how-to-implement-global-error-handling-in-vue – Alexander Nied Aug 19 '20 at 05:08

1 Answers1

1

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
});
Rahul Pal
  • 476
  • 3
  • 10