gkpo
gkpo

Reputation: 2662

Axios - Prevent .then() from executing on http errors

My problem:

I have set up an interceptor to catch error codes in HTTP responses. When the JWT expires, I have a code 401 coming back from the server. Here's my interceptor:

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)
    })
  }
})

My interceptor works fine, except the request that is being intercepted still resolves into the .then() part.

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

From the axios documentation, I found out you can prevent this by calling

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

But this is pretty verbose and I don't want to do this on every request that my app makes.

My question is:

How do I prevent axios from executing the .then() callback when I have an error. Is it something I can do in the interceptor? Like event.stopPropagation() or something like that?

Upvotes: 7

Views: 3336

Answers (3)

user7478383
user7478383

Reputation: 43

You can prevent the Axios Error by using the below set of code

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)
  }
})

Upvotes: 3

za-ek
za-ek

Reputation: 475

Throw an exception from catch block to prevent 'then' block

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
})

Upvotes: 1

Anonym
Anonym

Reputation: 107

Did you try catch in the end of the chain? You will get following

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`
})

Upvotes: 2

Related Questions