Reputation: 162
When i catch a error in nuxt/axios plugin, i call the error function provided in context to show error page, but except the 404 error, when the request failed with other status code(ex: 403), the request from node is always Status Code: 500 NuxtServerError
, and the custom error page not show as expect.
$axios.onError(err => {
console.log('error:', err); // error: Request failed with status code 403
// const code = parseInt(err.response && err.response.status)
// if(code === 403) {
// error({ statusCode: 403, message: 'WTF' })
// }
error({ statusCode: 403, message: 'WTF' })
})
But it always show NuxtServerError page. How to show my custom error page as expect?
update: even always call error function does not help
demo here: https://codesandbox.io/s/r75v2100lp
add a terminal tab, then execute npm run dev
Upvotes: 2
Views: 2638
Reputation: 641
This solved my problem
export default function ({ $axios, $store }: any) {
$axios.onError((error: any) => {
if (
error.response.code === 401 ||
error.response.detail === 'Something'
) {
$store.dispatch('auth/modal', error.response.code)
}
alert(error.response.data.message)
return { ...error.response, success: false }
})
$axios.onResponse((response: any) => {
return { ...response, success: true }
})
}
and in the component:
const login = async (): Promise<void> => {
await $axios
?.$post("/api/login", {
mobile: mobile.value,
})
.then((response: any) => {
if (response.ok) {
console.log(response);
}
});
};
Upvotes: 0
Reputation: 1637
If you don't want to get a Nuxt server error you should return something in the onError handler. for example, you maybe return false or true after handling the error in the onError handler.
create a plugin like axios.js in the plugin folder:
export default function ({app, store, $axios, redirect })
{
$axios.onError(
(error) => {
console.log(error.response);
// handle your errors here
// maybe you maybe reject promise
return Promise.reject(error.response);
// Or just return true or false
// return false
}
);
}
If you don't want to return anything so you should handle request wherever they've been called:
this.$axios.$post(`/api/calendars/events/`, this.event_data).then(
(data) => {
// do anything after request
this.clear_form()
}
)
You don't need to handle errors here just handle them in the axios.js plugin.
Upvotes: 1
Reputation: 10536
We should not throw error in nuxtServerInit
to keep init success. We could handling the error occured in nuxtServerInit
in try catch and do whatever from catch based on code
try {
const res = await this.$axios.$get("http://httpstat.us/403");
console.log("res:", res);
commit("SET_RES", res);
} catch(e){
console.log("handle error:"+ e)
}
here is the sandbox https://codesandbox.io/s/rj23o8ynwq
Upvotes: 0