错误处理

页面

404

页面级的错误处理由 vue-router 统一处理,所有匹配不到正确路由的页面都会进 404页面。

  1. { path: '*', redirect: '/404' }

WARNING

注意事项 这里有一个需要非常注意的地方就是 404 页面一定要最后加载,如果放在 constantRouterMap 一同声明了 404 ,后面的所以页面都会被拦截到404 ,详细的问题见 addRoutes when you've got a wildcard route for 404s does not work

401

@/permission.js做了权限控制,所有没有权限进入该路由的用户都会被重定向到 401页面。

请求

项目里所有的请求都会走@/utils/request.js里面创建的的 axios 实例,它统一做了错误处理,完整代码

你可以在service.interceptors.response response 拦截器之中根据自己的实际业务统一针对不同的状态码或者根据自定义 code 来做错误处理。如:

  1. service.interceptors.response.use(
  2. response => {
  3. /**
  4. * code为非20000是抛错 可结合自己业务进行修改
  5. */
  6. const res = response.data
  7. if (res.code !== 20000) {
  8. Message({
  9. message: res.data,
  10. type: 'error',
  11. duration: 5 * 1000
  12. })
  13. // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
  14. if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  15. MessageBox.confirm(
  16. '你已被登出,可以取消继续留在该页面,或者重新登录',
  17. '确定登出',
  18. {
  19. confirmButtonText: '重新登录',
  20. cancelButtonText: '取消',
  21. type: 'warning'
  22. }
  23. ).then(() => {
  24. store.dispatch('FedLogOut').then(() => {
  25. location.reload() // 为了重新实例化vue-router对象 避免bug
  26. })
  27. })
  28. }
  29. return Promise.reject('error')
  30. } else {
  31. return response.data
  32. }
  33. },
  34. error => {
  35. console.log('err' + error) // for debug
  36. Message({
  37. message: error.message,
  38. type: 'error',
  39. duration: 5 * 1000
  40. })
  41. return Promise.reject(error)
  42. }
  43. )

因为所有请求返回的是promise,所以你也可以对每一个请求通过catch 错误,从而进行单独的处理。

  1. getInfo()
  2. .then(res => {})
  3. .catch(err => {
  4. xxxx
  5. })

代码

本项目也做了代码层面的错误处理,如果你开启了eslint在编写代码的时候就会提示错误。如:错误处理 - 图1

当然还有很多不能被eslint检查出来的错误,vue 也提供了全局错误处理钩子errorHandler,所以本项目也做了相对应的错误收集。错误处理 - 图2

TIP

监听错误:@/errorLog.js

错误展示组件:@/components/ErrorLog

原文: https://panjiachen.github.io/vue-element-admin-site/zh/guide/advanced/error.html