error-handler.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * 网络请求异常处理程序
  3. */
  4. import { RequestError } from '@@/plugin-request/request';
  5. import { notification } from 'antd';
  6. import { ArgsProps } from 'antd/lib/notification/index';
  7. /**
  8. * @description: 业务异常码 and http状态码
  9. * @param {number}
  10. */
  11. const codeMessage: {
  12. [key: number]: string;
  13. } = {
  14. '200': '服务器成功返回请求的数据',
  15. '401': '认证失败。',
  16. '403': '用户得到授权,但是访问是被禁止的。',
  17. '500': '服务器发生错误,请检查服务器。',
  18. '502': '网关错误。',
  19. '503': '服务不可用,服务器暂时过载或维护。',
  20. '504': '网关超时。',
  21. '-1001': '导入失败'
  22. };
  23. interface error {
  24. name: string;
  25. data: any;
  26. type: string;
  27. response: {
  28. code: any;
  29. status: any;
  30. msg: string;
  31. };
  32. }
  33. const notificationMap = new Map();
  34. /**
  35. * 推送消息
  36. * @param option ArgsProps
  37. */
  38. function pushNotification(option: ArgsProps) {
  39. notificationMap.set(option.message, option);
  40. setTimeout(() => {
  41. const key = notificationMap.keys().next().value;
  42. const val = notificationMap.get(key);
  43. if (val) {
  44. notificationMap.delete(key);
  45. notification.error(val);
  46. }
  47. }, 1000);
  48. }
  49. /**
  50. * 异常处理程序
  51. */
  52. const errorHandler = (error: RequestError | any, opts: any) => {
  53. if (opts?.skipErrorHandler) throw error;
  54. if (error.name === 'BizError') {
  55. pushNotification({
  56. message: error.message || '接口错误!'
  57. });
  58. } else if (error.response) {
  59. const errorText = codeMessage[error.response.status];
  60. pushNotification({
  61. message: errorText || '接口错误!'
  62. });
  63. } else if (error.request) {
  64. pushNotification({
  65. message: '接口超时!'
  66. });
  67. } else {
  68. pushNotification({
  69. message: '网络异常'
  70. });
  71. }
  72. throw error;
  73. };
  74. export default errorHandler;