# 錯誤處理
## [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/error.html#%E9%A1%B5%E9%9D%A2)頁面
**404**
頁面級的錯誤處理由`vue-router`統一處理,所有匹配不到正確路由的頁面都會進`404`頁面。
~~~
{ path: '*', redirect: '/404' }
~~~
> WARNING
>
> **注意事項**這里有一個需要非常注意的地方就是`404`頁面一定要最后加載,如果放在 constantRoutes 一同聲明了`404`,后面的所有頁面都會被攔截到`404`,詳細的問題見[addRoutes when you've got a wildcard route for 404s does not work](https://github.com/vuejs/vue-router/issues/1176)
**401**
在`@/permission.js`做了權限控制,所有沒有權限進入該路由的用戶都會被重定向到`401`頁面。
## [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/error.html#%E8%AF%B7%E6%B1%82)請求
項目里所有的請求都會走`@/utils/request.js`里面創建的的 axios 實例,它統一做了錯誤處理,[完整代碼](https://github.com/PanJiaChen/vue-element-admin/blob/master/src/utils/request.js)。
你可以在`service.interceptors.response`response 攔截器之中根據自己的實際業務統一針對不同的狀態碼或者根據自定義 code 來做錯誤處理。如:
~~~
service.interceptors.response.use(
response => {
/**
* code為非20000是拋錯 可結合自己業務進行修改
*/
const res = response.data
if (res.code !== 20000) {
Message({
message: res.data,
type: 'error',
duration: 5 * 1000
})
// 50008:非法的token; 50012:其他客戶端登錄了; 50014:Token 過期了;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
MessageBox.confirm(
'你已被登出,可以取消繼續留在該頁面,或者重新登錄',
'確定登出',
{
confirmButtonText: '重新登錄',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload() // 為了重新實例化vue-router對象 避免bug
})
})
}
return Promise.reject('error')
} else {
return response.data
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
~~~
因為所有請求返回的是`promise`,所以你也可以對每一個請求通過`catch`錯誤,從而進行單獨的處理。
~~~
getInfo()
.then(res => {})
.catch(err => {
xxxx
})
~~~
## [#](https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/error.html#%E4%BB%A3%E7%A0%81)代碼
本項目也做了代碼層面的錯誤處理,如果你開啟了`eslint`在編寫代碼的時候就會提示錯誤。如:
當然還有很多不能被`eslint`檢查出來的錯誤,vue 也提供了全局錯誤處理鉤子[errorHandler](https://vuejs.org/v2/api/#errorHandler),所以本項目也做了相對應的錯誤收集。
> ## TIP
>
> 監聽錯誤:[@/errorLog.js](https://github.com/PanJiaChen/vue-element-admin/blob/master/src/errorLog.js)
>
> 錯誤展示組件:[@/components/ErrorLog](https://github.com/PanJiaChen/vue-element-admin/blob/master/src/components/ErrorLog/index.vue)