我的问题:
我已经设置了一个拦截器来捕获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)
})
}
})
我的拦截器工作得很好,只是被拦截的请求仍然解析为.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
})
从axios文档中,我发现你可以通过调用来防止这种情况
this.axios.get('/texts').then(function(){
// only on success
}).catch(function(){
// only on errors
}).then(function(){
// always executed
})
但这相当冗长,我不想对我的应用程序发出的每一个请求都这样做。
我的问题是:
当我出现错误时,如何防止axios执行.then((回调。这是我可以在拦截器中做的事情吗?比如event.stopPropagation((之类的?
您可以通过使用以下代码集来防止Axios错误
this.axios.interceptors.response.use(undefined, (error) => {
if (error.response.status === 401) {
this.$store.dispatch('auth/logout').then(() => {
this.$router.push({name: 'login'})
return new Promise(() => { });
})
} else {
return Promise.reject(error)
}
})
从catch块抛出异常以阻止"then"块
this.axios.get('/texts').then(function(){
// only on success
}).catch(function(e){
// only on errors
throw e;
}).then(function(){
// Will not executed if there is an error but yes on success
})
您在链的末端尝试过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`
})