Axios - 防止 .then() 在 http 错误上执行

Mon*_*nja 7 javascript interceptor promise axios

我的问题:

我已经设置了一个拦截器来捕获 HTTP 响应中的错误代码。当 JWT 到期时,我有一个从服务器返回的代码 401。这是我的拦截器:

this.axios.interceptors.response.use(undefined, (error) => {
  if (error.response.status === 401) {
    this.$store.dispatch('auth/logout').then(() => {
      this.$router.push({name: 'login'})
      return Promise.reject(error)
    })
  }
})
Run Code Online (Sandbox Code Playgroud)

我的拦截器工作正常,除了被拦截的请求仍然解析为 .then() 部分。

this.axios.get('/texts').then(function(){
    // This is still being executed and generates javascript errors because the response doesn't contain the right data
})
Run Code Online (Sandbox Code Playgroud)

从 axios 文档中,我发现您可以通过调用来防止这种情况发生

this.axios.get('/texts').then(function(){
    // only on success
}).catch(function(){
    // only on errors
}).then(function(){
    // always executed
})
Run Code Online (Sandbox Code Playgroud)

但这非常冗长,我不想对我的应用程序发出的每个请求都执行此操作。

我的问题是:

出现错误时如何防止 axios 执行 .then() 回调。我可以在拦截器中做些什么吗?像 event.stopPropagation() 或类似的东西?

小智 2

你尝试catch过链的末端吗?您将得到以下信息

this.axios.get('/texts').then(function(){
    // only on success
}).then(function(){
    // only on success in previous then 
}).catch(function(){
    // executes on every error from `get` and from two previous `then`
})
Run Code Online (Sandbox Code Playgroud)