Yevgeniy
Yevgeniy

Reputation: 24

What are the best practices for handling vuex errors?

I'm new to vue. I use interceptors for handling action responses, all easy with successful responses. But I would like to know what are the best practice to handle error responses. I want to show a toastr with error message from response by default if there's no catch block in the action, but if there is a catch, do only catch function with no toastr shown. Also, is it ok to handle unauthorized response making a redirect to login page directly in interceptor and what advices can be given about it? My current interceptor looks like this:

axios.interceptors.response.use(
      (response) => {
        return response.data.data;
      },
      (error: AxiosError) => {
        const data = error.response?.data;
        const code = data?.code;
        if (code === ErrorCodes.NEED_EMAIL_CONFIRMATION) {
          router.push("email-verification").then();
        } else if (code === ErrorCodes.UNAUTHORIZED) {
          router.push("sign-in").then();
        } else {
          if (undefined !== data.error) {
            toaster.error(data.error);
          } else {
            toaster.error(i18n.t("unexpected"));
          }
        }
        return error;
      }
    );

but I don't like too many responsibilities here and I don't know how to avoid toastr show when the action has a catch function

Upvotes: 0

Views: 217

Answers (1)

mendmania
mendmania

Reputation: 30

You can control error toast notification from where you send the request, by sending an extra config.

Using axios:

  axios.post('/api-name', data, {
    config: {
      showToast: true,
    },
  })

and then on axios intercept:

axios.interceptors.response.use( 
response => {...},
error => {
   const showTost= error.config.errorToast
   if(showToast){
     // show toast you can pass custom message too...<3
   }
}

Upvotes: 1

Related Questions