Skip to content

Instantly share code, notes, and snippets.

@cryocaustik
Created July 29, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cryocaustik/49c9e39bee2a16b3fa69e78716ae5105 to your computer and use it in GitHub Desktop.
Save cryocaustik/49c9e39bee2a16b3fa69e78716ae5105 to your computer and use it in GitHub Desktop.
axios interaceptor to catch errors and perform something on specific cases, returning the error response in all other cases
axios.interceptors.response.use(
response => {
return response
},
error => {
console.log(`interceptor: response | ${error.config.url}`)
if (
error.config &&
!error.config.url.endsWith('/refresh') &&
!error.config.url.endsWith('/token') &&
!error.config.url.endsWith('/register') &&
error.response.status === 401 &&
store.getters.isLoggedIn &&
store.state.refreshAttempts < 3
) {
store.state.refreshAttempts += 1
return store.dispatch('refreshToken').then(() => {
store.state.refreshAttempts = 0
return new Promise((resolve, reject) => {
axios
.request(error.config)
.then(resp => {
resolve(resp)
})
.catch(err => {
reject(err)
})
})
})
} else {
console.log(`interceptor: response| returning response | ${JSON.stringify(error)}`)
return error
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment