UmiJs的统一异常处理和全局的接口异常处理

统一异常处理:

本项目中是根据umijs/plugin-request进行的网络请求.他们后端接口返回数据有着统一的规范.

interface ErrorInfoStructure {
  success: boolean; // if request is success
  data?: any; // response data
  errorCode?: string; // code for errorType
  errorMessage?: string; // message display to user 
  showType?: number; // error display type: 0 silent; 1 message.warn; 2 message.error; 4 notification; 9 page
  traceId?: string; // Convenient for back-end Troubleshooting: unique request ID
  host?: string; // Convenient for backend Troubleshooting: host of current access server
}

但是当我们的后端接口返回的数据规范不满足的情况下,我们可以通过配置  errorConfig.adaptor  来做适配.

在 app.tsx 中引入一下:

export const request: RequestConfig = { // 请求配置
  errorConfig: { // 错误处理
    adaptor: (resData) => { // 适配器
      return {
        ...resData, // 适配器里面要返回一个对象,里面包含了 success 和 errorMessage
        success: resData.ok, // 这里的 success 表示是否请求成功
        errorMessage: resData.message, // 这里的 errorMessage 表示错误信息
      };
    },
  },
};

当后端接口不满足该规范的时候你需要通过该配置把后端接口数据转换为该格式,该配置只是用于错误处理,不会影响最终传递给页面的数据格式.

全局的接口异常处理:

在  app.tsx 中引入一下:

export const request: RequestConfig = { // 请求配置
  errorHandler: (error) => { // errorHandler: 异常处理程序
    // console.log('error:',error)
    const { response } = error;
    if (response && response.status) {
      // const errorText = codeMessage[response.status] || response.statusText;
      const { status, url } = response;
      message.error(`请求错误 ${status}: ${url}`)
      /*notification.error({ //右侧提示框 notification需要 import { notification } from 'antd';
        message: `请求错误 ${status}: ${url}`,
        description: errorText,
      });*/
    }
    if (!response) {
      message.error('您的网络发生异常,无法连接服务器')
      /*notification.error({ // 右侧提示框
        description: '您的网络发生异常,无法连接服务器',
        message: '网络异常',
      });*/
    }
    throw error;
  },
};

当接口报500时,就会提示你所要显示的内容.

猜你喜欢

转载自blog.csdn.net/m0_58293192/article/details/130238256