首页 > 解决方案 > 在 vuejs 中使用 axios 进行全局错误处理

问题描述

我在 vuejs 中使用 axios,并且在 axios 调用时遇到全局错误处理问题。我正在尝试如下,它不仅需要用户注销,而且还在 axios 调用后执行代码块。如果发生错误,如何防止执行 axios 调用承诺代码部分。

export default {
    created() {
    var self = this;
      if (self.$route.meta.requiresAuth) {
        axios.interceptors.response.use(
          function(response) {
            return response;
          },
          function(error) {
            if (error.response.status == 401) {
              self.$toaster.error("ERROR: Invalid token detected");
                self.logout();
              }
            }
          );
        }
      },
      methods: {
        logout() {
          this.$router.push({ name: "login" });
        }
      }
    }

someFunction() {
  var self = this;
  axios
    .post(
      "url/to/api",
      {},
      {
        headers: {
          Authorization: "authtoken here"
        }
      }
    )
    .then(response => {
      alert("success");
        otherFunction();
      })
      .catch(error => {
        console.log(error);
      });
}

标签: vue.jsaxios

解决方案


您将需要从错误拦截器中引发一个新错误。

axios.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    if (error.response.status == 401) {
      self.$toaster.error("ERROR: Invalid token detected");
        self.logout();
      }
      throw new Error('Invalid token detected')
    }
  );
}

推荐阅读