Глобальная обработка ошибок с помощью axios в vuejs - PullRequest
0 голосов
/ 11 сентября 2018

Я использую axios в vuejs и у меня проблемы с глобальной обработкой ошибок при вызове 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);
      });
}

1 Ответ

0 голосов
/ 11 сентября 2018

Вам нужно будет поднять новую ошибку от перехватчика ошибок.

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')
    }
  );
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...