Selaa lähdekoodia

refactor: responseInterceptors support throw error

lanjianrong 3 vuotta sitten
vanhempi
commit
081f33c0e4
1 muutettua tiedostoa jossa 47 lisäystä ja 18 poistoa
  1. 47 18
      src/app.tsx

+ 47 - 18
src/app.tsx

@@ -49,31 +49,60 @@ const authHeaderInterceptor = options => {
   return options
 }
 
-const errorHandler = response => {
-  if (consts.TOKEN_INVALID_CODE.includes(response.code) && window.location.pathname !== consts.loginPath) {
+const errorHandler = (error: any, opts: any) => {
+  if (opts?.skipErrorHandler) return
+
+  const errorInfo = error.info
+  if (errorInfo) {
+    const { errorMessage = '请求失败', errorCode } = errorInfo
+    if (errorCode.includes(response.code) && window.location.pathname !== consts.loginPath) {
+      notification.error({
+        message: '用户信息过期',
+        description: '请重新登录'
+      })
+      history.replace({
+        pathname: consts.loginPath,
+        search: createSearchParams({
+          redirect: window.location.pathname
+        }).toString()
+      })
+      return
+    }
+    notification.error({
+      message: title,
+      description: errorMessage
+    })
+  } else if (error.response) {
+    // Axios 的错误
+    // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
     notification.error({
-      message: '用户信息过期',
-      description: '请重新登录'
+      description: `状态码为${error.status}, 请联系管理员进行处理`,
+      message: '请求异常'
     })
-    history.replace({
-      pathname: consts.loginPath,
-      search: createSearchParams({
-        redirect: window.location.pathname
-      }).toString()
+  } else if (error.request) {
+    // 请求已经成功发起,但没有收到响应
+    // 或请求根本没有发送出去
+    notification.error({
+      description: '您的网络请求已经发起,但没有收到响应',
+      message: '响应超时'
+    })
+  } else {
+    notification.error({
+      description: '您的网络发生异常,无法连接服务器',
+      message: '网络异常'
     })
-    return
   }
-  notification.error({
-    message: '请求失败',
-    description: response.msg
-  })
-  return
 }
 
 const responseInterceptor = response => {
-  const { code = -1 } = response?.data || {}
-  if (code !== consts.RET_CODE.SUCCESS) {
-    return Promise.reject(response?.data)
+  const { data, code: errorCode, msg: errorMessage } = response.data
+  if (!errorCode || errorCode !== consts.RET_CODE.SUCCESS) {
+    if (errorCode !== consts.RET_CODE.SUCCESS) {
+      const error: any = new Error(errorMessage)
+      error.name = 'BizError'
+      error.info = { errorCode, errorMessage, data }
+      throw error
+    }
   }
   return Promise.resolve(response)
 }