Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 929
gkpo Avatar asked Nov 19 '18 09:11

gkpo


People also ask

How do you handle errors in Axios?

axios. get('/user/12345') . catch(function (error) { if (error.

Does Axios catch 400 error?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step.

Does Axios throw error on 404?

By default, axios throws an error when it encounters any 4XX / 5XX status code. Adding this line overrides that default behavior. You can then check the status code yourself (in response. status ), conditionally handling the 404 as you need.

How do you handle Axios requests?

To perform an HTTP POST request in Axios, call axios. post() . Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server. For a simple Axios POST request, the object must have a url property.


1 Answers

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)
  }
})
like image 112
user7478383 Avatar answered Sep 28 '22 18:09

user7478383