axios-module: Globally capture errors
Version
Reproduction link
https://axios.nuxtjs.org/extend
Steps to reproduce
Follow setting axios from nuxt documentary.
What is expected ?
Whenever we catch the error inside $axios.onError we should redirect to the given route. I could handle the error on each request by catching it, but as far as we got global handler we should be able to catch it in one place.
What is actually happening?
It is throwing NuxtServerError.
[Axios] Response error: Request failed with status code 401
09:59:32
at createError (node_modules/axios/lib/core/createError.js:16:15)
at settle (node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:201:11)
at IncomingMessage.emit (events.js:202:15)
at IncomingMessage.EventEmitter.emit (domain.js:481:20)
at endReadableNT (_stream_readable.js:1132:12)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
Additional comments?
I would like to add my code to describe more precisely situation:
I have registered axios module and extended it:
plugins: [
'~plugins/axios',
],
modules: [
'@nuxtjs/axios',
],
The plugin:
const EXPIRED_TOKEN_MESSAGE = 'Expired JWT Token';
export default function ({
$axios, redirect, app, store,
}) {
$axios.setHeader('Content-Type', 'application/json');
$axios.setHeader('Accept', 'application/json');
$axios.onRequest((config) => {
console.log(`Making request to ${config.url}`);
});
$axios.onError((error) => {
const { response: { data: { message } } } = error;
if (message === EXPIRED_TOKEN_MESSAGE) {
store.dispatch('authentication/logout');
}
store.dispatch('alerts/addAlert', { type: 'error', message });
});
}
The store:
logout({ commit }) {
Cookie.remove('jwt');
commit('setUser', null);
commit('data/clearStorage', {}, { root: true });
this.$router.push({ name: 'index' });
},
<div align="right">This bug report is available on Nuxt community (#c235)</div>About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 2
- Comments: 19 (8 by maintainers)
Commits related to this issue
- Document global error handling in interceptors Re: https://github.com/nuxt-community/axios-module/issues/241#issuecomment-742822630 — committed to marcvangend/axios-module by marcvangend 4 years ago
- docs: explain global error handling in interceptors (#453) * Document global error handling in interceptors Re: https://github.com/nuxt-community/axios-module/issues/241#issuecomment-742822630 ... — committed to nuxt-community/axios-module by marcvangend 4 years ago
While it is not really recommended to globally suppress errors what you can do is:
It will cause if
$axiosrequests failing, return an empty object for data anderroris available in reponse object but nothing throws anymore.Hi @marcvangend It is because you need to resolve response in error interceptor otherwise it will be simply just intercepted (for logging or show an alert). So this fixes issue: (sandbox)
If you wish to update docs noticing this, would be awesome đ
Hi. You have to handle the error. Maybe returning an empty object at the end of
onErrorhandler.Ah, excellent, thank you @pi0! At least itâs reassuring to see that I was pretty close đ
So if I understand correctly:
error()function earlier. (That last bit it what caused my confusion, I guess.)I will try to submit a PR for the docs.
i solved this problem with error catcher in fetch request
Sorry for bumping a closed issue, but Iâm seeing similar issues and Iâd really like to understand how things are supposed to work.
I prepared a CodeSandbox, I hope @pi0 you are able to have a look: https://codesandbox.io/s/floral-voice-flh6f?file=/pages/fail.vue. It uses a plugin
$apiClientto handle api calls with Axios, the structure of which is based on this post: Organize and decouple your API calls in Nuxt.js. This plugin also adds error handling using the onError interceptor. Two pages (working.vue and fail.vue) use this apiClient to retrieve data. One works but the other uses an incorrect id on purpose, causing a 404 response from the api server. I expect this error to be handled by the onError hook.Now my question⌠The only way I was able to get the error handling to work, was by adding
.catch()in my asyncData hook like this:As you can see the
.catch(() => false);line doesnât do much, but without it, the Axios error handler doesnât kick in. Is this how itâs supposed to be? How does this work? Shouldnât the onError interceptor take simply care of things, regardless of what happens in asyncData?Thank you for your time and support.
I found what is the problem:
nuxtServerInitis running into infinity loop. I do have authentication copy pasted from Nuxt guide the only thing I have added is Axios interceptor helpers based on newest approach.Axios.js plugin:
Vuex store authentication actions:
Vuex store authentication state:
And the two middleware:
authenticated.js added into default layout
notAuthenticated added into login layout
Expected action:
When the axios onError interceptor is hit it should logout user.
What is happening:
nuxtServerInit is keep running at the infinity loop - even when cookies are removed, the seems to be passed into req.headers.cookie.
Any approach for my case ? I would be grateful @pi0
It is only occurring at the server side when page is refreshed and token invalidated - when we are in the app, after token invalidates the behaviour is correct.
It works as expected.
Promise.rejectmeans also throwing an error (promise chain).As this is a global handler, you have to check response when using.