在vuejs中使用axios的全局错误处理

问题描述 投票:0回答:1

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

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.js axios
1个回答
0
投票

您需要从错误拦截器引发新错误。

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')
    }
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.