responseHandler.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {ApiResponse} from "@/api/types";
  2. import {AxiosError, AxiosResponse} from "axios";
  3. import {BusinessErrCode, businessErrCodeMsgKV, ErrCode, errCodeMsgKV} from "@/utils/request/errcode";
  4. import 'vant/es/notify/style'
  5. import { showNotify } from 'vant';
  6. /**
  7. * 处理resp.data.code不为200
  8. *
  9. * @returns 返回响应success
  10. */
  11. export function handleInnerCodeErr(respData:ApiResponse) {
  12. if(respData.code != 200) {
  13. // 展示默认错误提示信息
  14. const outMsgInfo = businessErrCodeMsgKV[respData.code as BusinessErrCode]
  15. if(outMsgInfo) {
  16. // 提示错误信息
  17. showNotify({ type: 'warning', message: respData.msg });
  18. }else {
  19. showNotify({ type: 'warning', message:'服务器发生了错误,请重试' });
  20. }
  21. return false
  22. }
  23. return true
  24. }
  25. /**
  26. * 处理http响应码为200的响应
  27. */
  28. export const handleNormalResponse = async (resp:AxiosResponse<ApiResponse>) => {
  29. // 处理已知错误码
  30. if (resp?.data?.code) {
  31. switch (resp.data.code) {
  32. case ErrCode.UNAUTHORIZED:
  33. // 执行登出操作
  34. break
  35. }
  36. }
  37. // 如果发现屏蔽内部错误处理标记打开,则直接放行
  38. if (resp.config.maskingErrorInterceptors) return true
  39. // 处理resp.data.success为false的情况
  40. return handleInnerCodeErr(resp.data)
  41. }
  42. /**
  43. * 处理http响应码不为200的响应
  44. */
  45. export const handleHttpError = (err:AxiosError) => {
  46. if(err.code === 'ECONNABORTED') {
  47. return Promise.reject(err)
  48. }
  49. // 展示默认错误提示信息
  50. const msg = errCodeMsgKV[err.response?.status as ErrCode]
  51. if(err.code === 'ECONNABORTED' && err.message.includes('timeout')) {
  52. showNotify({ type: 'warning', message: '请求超时,请重试!' });
  53. }else if(err.message === 'Network Error') {
  54. showNotify({ type: 'warning', message: '服务器错误或网络错误, 请稍后再试!' });
  55. }else if(msg) {
  56. showNotify({ type: 'warning', message: msg });
  57. }else {
  58. showNotify({ type: 'warning', message: '服务器发出了未知错误!' });
  59. }
  60. return Promise.reject(err)
  61. }