Browse Source

fix: 调整RequestConfig,为了兼容useRequest的用法

lanjianrong 4 years ago
parent
commit
aeeab1c3d7
1 changed files with 60 additions and 65 deletions
  1. 60 65
      src/app.tsx

+ 60 - 65
src/app.tsx

@@ -11,9 +11,18 @@ import consts from './consts'
 import ModalStore from './components/ModalStore'
 import MessageDetail from './pages/Hr/Notification/components/MessageDetail'
 import defaultSettings from '../config/defaultSettings'
-import type { ErrorShowType, RequestConfig } from '@umijs/max'
+import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max'
+import type { AxiosResponse } from './.umi/plugin-request/request'
 
 const loginPath = '/user/login'
+// 错误处理方案: 错误类型
+enum ErrorShowType {
+  SILENT = 0,
+  WARN_MESSAGE = 1,
+  ERROR_MESSAGE = 2,
+  NOTIFICATION = 3,
+  REDIRECT = 9
+}
 export async function getInitialState() {
   // 如果是登录页面,不执行
   const fetchUserInfo = async () => {
@@ -55,7 +64,7 @@ export async function getInitialState() {
   }
 }
 
-export const layout = ({ initialState, setInitialState }) => {
+export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState, loading }) => {
   const onCollapse = collapsed => {
     setInitialState({ ...initialState, settings: { ...initialState.settings, collapsed } })
     setAuthCache(LAYOUT_COLLAPSED_KEY, collapsed)
@@ -63,6 +72,7 @@ export const layout = ({ initialState, setInitialState }) => {
 
   return {
     logo,
+    loading,
     rightContentRender: () => (
       <ModalStore _modalMap={{ D_NOTICE_DETAIL: MessageDetail }}>
         <RightContent />
@@ -95,56 +105,53 @@ export const layout = ({ initialState, setInitialState }) => {
 }
 
 let notificationLimit = 0 // 最大1
-const errorHandler = (error: any, opts: any) => {
-  if (opts?.skipErrorHandler) throw error
-  if (error.name === 'BizError') {
-    const errorInfo = error.info
-    if (errorInfo) {
-      if (notificationLimit >= 1) {
-        return
-      }
-      const { errorMessage = '请求失败', showType, errorCode } = info
-      if (consts.TOKEN_INVALID_CODE.includes(errorCode) && window.location.pathname !== loginPath) {
-        history.replace({
-          pathname: loginPath,
-          search: createSearchParams({ redirect: window.location.pathname }).toString()
-        })
-      }
-      switch (showType) {
-        case ErrorShowType.ERROR_MESSAGE:
-          message.error(errorMessage)
-          break
-        case ErrorShowType.WARN_MESSAGE:
-          message.warn(errorMessage)
-          break
-        case ErrorShowType.NOTIFICATION:
-          if (!notificationLimit) {
-            const title = consts.TOKEN_INVALID_CODE.includes(errorCode) ? '用户信息过期' : '请求失败'
-            notification.error({
-              message: title,
-              description: errorMessage
-            })
-            notificationLimit++
-          }
-          break
-        default:
-          break
-      }
-    } else if (error.response) {
-      // Axios 的错误
-      // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
-      notification.error({
-        description: `状态码为${error.response.status}, 请联系管理员进行处理`,
-        message: '请求异常'
-      })
-    } else {
-      // 请求已经成功发起,但没有收到响应
-      // 或请求根本没有发送出去
-      notification.error({
-        description: '您的网络发生异常,无法连接服务器',
-        message: '网络异常'
+const errorHandler = (error: AxiosResponse) => {
+  const errorInfo = error.data
+  if (errorInfo) {
+    if (notificationLimit >= 1) {
+      return
+    }
+    const { msg: errorMessage = '请求失败', showType, code: errorCode } = errorInfo
+    if (consts.TOKEN_INVALID_CODE.includes(errorCode) && window.location.pathname !== loginPath) {
+      history.replace({
+        pathname: loginPath,
+        search: createSearchParams({ redirect: window.location.pathname }).toString()
       })
     }
+    switch (showType) {
+      case ErrorShowType.ERROR_MESSAGE:
+        message.error(errorMessage)
+        break
+      case ErrorShowType.WARN_MESSAGE:
+        message.warn(errorMessage)
+        break
+      case ErrorShowType.NOTIFICATION:
+        if (!notificationLimit) {
+          const title = consts.TOKEN_INVALID_CODE.includes(errorCode) ? '用户信息过期' : '请求失败'
+          notification.error({
+            message: title,
+            description: errorMessage
+          })
+          notificationLimit++
+        }
+        break
+      default:
+        break
+    }
+  } else if (error.status) {
+    // Axios 的错误
+    // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
+    notification.error({
+      description: `状态码为${error.status}, 请联系管理员进行处理`,
+      message: '请求异常'
+    })
+  } else {
+    // 请求已经成功发起,但没有收到响应
+    // 或请求根本没有发送出去
+    notification.error({
+      description: '您的网络发生异常,无法连接服务器',
+      message: '网络异常'
+    })
   }
 }
 const authHeaderInterceptor = (options: any) => {
@@ -160,19 +167,6 @@ const authHeaderInterceptor = (options: any) => {
 }
 
 export const request: RequestConfig = {
-  errorConfig: {
-    // 错误抛出
-    errorThrower: (res: ResponseStructure) => {
-      const { data, code, msg, showType } = res
-      if (code !== consts.RET_CODE.SUCCESS) {
-        const error: any = new Error(errorMessage)
-        error.name = 'BizError'
-        error.info = { errorCode: code, errorMessage: msg, showType, data }
-        throw error // 抛出自制的错误
-      }
-    },
-    errorHandler
-  },
   baseURL: consts.PREFIX_URL,
   requestInterceptors: [authHeaderInterceptor],
   responseInterceptors: [
@@ -186,8 +180,9 @@ export const request: RequestConfig = {
         notificationLimit = 0
       }
       const { code = -1 } = response?.data || {}
-      if (code !== consts.RET_CODE.SUCCESS) {
-        return Promise.reject(response?.data)
+      if (response.status !== 200 || code !== consts.RET_CODE.SUCCESS) {
+        errorHandler(response)
+        return Promise.reject(response.data?.msg)
       }
       return Promise.resolve(response)
     }