Duy Kieu
Duy Kieu

Reputation: 11

How can I avoid repeat catch function in Promise

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

Answers (1)

Rahul Pal
Rahul Pal

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

Related Questions