Procházet zdrojové kódy

fix: request不走throw errorHandler,返回原数据

lanjianrong před 4 roky
rodič
revize
6991e8d575

+ 23 - 11
src/app.tsx

@@ -12,7 +12,6 @@ import ModalStore from './components/ModalStore'
 import MessageDetail from './pages/Hr/Notification/components/MessageDetail'
 import defaultSettings from '../config/defaultSettings'
 import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max'
-import type { AxiosResponse } from './.umi/plugin-request/request'
 
 const loginPath = '/user/login'
 // 错误处理方案: 错误类型
@@ -105,13 +104,15 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState, loa
 }
 
 let notificationLimit = 0 // 最大1
-const errorHandler = (error: AxiosResponse) => {
-  const errorInfo = error.data
+
+const errorHandler = (error: any, opts: any) => {
+  if (opts?.skipErrorHandler) throw error
+  const errorInfo = error.info
   if (errorInfo) {
     if (notificationLimit >= 1) {
       return
     }
-    const { msg: errorMessage = '请求失败', showType, code: errorCode } = errorInfo
+    const { errorMessage = '请求失败', showType, errorCode } = errorInfo
     if (consts.TOKEN_INVALID_CODE.includes(errorCode) && window.location.pathname !== loginPath) {
       history.replace({
         pathname: loginPath,
@@ -138,22 +139,28 @@ const errorHandler = (error: AxiosResponse) => {
       default:
         break
     }
-  } else if (error.status) {
+  } else if (error.response) {
     // Axios 的错误
     // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
     notification.error({
       description: `状态码为${error.status}, 请联系管理员进行处理`,
       message: '请求异常'
     })
-  } else {
+  } else if (error.request) {
     // 请求已经成功发起,但没有收到响应
     // 或请求根本没有发送出去
     notification.error({
+      description: '您的网络请求已经发起,但没有收到响应',
+      message: '响应超时'
+    })
+  } else {
+    notification.error({
       description: '您的网络发生异常,无法连接服务器',
       message: '网络异常'
     })
   }
 }
+
 const authHeaderInterceptor = (options: any) => {
   const token = getToken()
   if (token) {
@@ -179,12 +186,17 @@ export const request: RequestConfig = {
       ) {
         notificationLimit = 0
       }
-      const { code = -1 } = response?.data || {}
-      if (response.status !== 200 || code !== consts.RET_CODE.SUCCESS) {
-        errorHandler(response)
-        return Promise.reject(response.data?.msg)
+
+      const { data, code: errorCode, msg: errorMessage, showType } = 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, showType, data }
+          errorHandler(error)
+        }
       }
-      return Promise.resolve(response)
+      return response
     }
   ]
 }

+ 4 - 4
src/pages/Customer/Client/components/ClientDetail/LowerList.tsx

@@ -76,7 +76,7 @@ type ServiceLogItemProps = {
 export const ServiceLogItem: React.FC<ServiceLogItemProps> = ({ item, logType, updatePayload }) => {
   const dispatchModal = useModal()
   const dispatch = useDispatch()
-  const { run: truUpdate } = useRequest(
+  const { run: tryUpdate } = useRequest(
     logType === ServiceLogType.COMPANY ? updateCustomerService : updateClientService,
     {
       manual: true,
@@ -88,7 +88,7 @@ export const ServiceLogItem: React.FC<ServiceLogItemProps> = ({ item, logType, u
       }
     }
   )
-  const { run: truDel } = useRequest(
+  const { run: tryDel } = useRequest(
     logType === ServiceLogType.COMPANY ? delCustomerService : delClientService,
     {
       manual: true,
@@ -102,7 +102,7 @@ export const ServiceLogItem: React.FC<ServiceLogItemProps> = ({ item, logType, u
   )
 
   const handleOnEdit = async (defaultValues: API.ServiceLogItem) => {
-    dispatchModal('M_RECORD_ADD', { defaultValues, onConfirm: truUpdate })
+    dispatchModal('M_RECORD_ADD', { defaultValues, onConfirm: tryUpdate })
   }
   return (
     <div
@@ -153,7 +153,7 @@ export const ServiceLogItem: React.FC<ServiceLogItemProps> = ({ item, logType, u
             <Button size="small" onClick={() => handleOnEdit(item)}>
               编辑
             </Button>
-            <Popconfirm title="确认删除该服务记录吗?" onConfirm={() => truDel({ id: item.id })}>
+            <Popconfirm title="确认删除该服务记录吗?" onConfirm={() => tryDel({ id: item.id })}>
               <Button size="small" danger className="ml-1">
                 删除
               </Button>

+ 28 - 35
src/pages/Product/Cloud/index.jsx

@@ -1,13 +1,13 @@
 /* eslint-disable no-underscore-dangle */
 import React, { useState, useEffect, useRef } from 'react'
 import BasicTable from '@/components/Table'
-import { dayjsFormat, generateSortField } from '@/utils/utils'
+import { dayjsFormat } from '@/utils/utils'
 import { queryRoadpricingList } from '@/services/product'
 import { Input, Tag, Tooltip } from 'antd'
-import consts from '@/consts'
-import { useLocation, useSelector, useDispatch } from '@umijs/max'
 import { useModal } from '@/components/ModalStore'
 import { PageContainer } from '@ant-design/pro-layout'
+import { useCreation } from 'ahooks'
+import { connect } from '@@/plugin-dva'
 
 export const roadpricingEnum = {
   CURING: 1, // 养护云
@@ -16,44 +16,36 @@ export const roadpricingEnum = {
   GS: 4 // 大司空概算
 }
 
-const Cloud = () => {
-  const { pathname = '' } = useLocation()
+const Cloud = ({ cloud, dispatch }) => {
   const tRef = useRef()
-  const columnStateType = pathname?.match(/\/([^/]*)$/)[1]?.toUpperCase()
-  const dispatch = useDispatch()
   const dispatchModal = useModal()
-  const { cloud } = useSelector(state => ({
-    cloud: state.cloud,
-    shouldUpdate: state.refresh.cloud
-  }))
-  const compilation = cloud.compilation[roadpricingEnum[columnStateType]]
-  const province = cloud.province[roadpricingEnum[columnStateType]]
-
   const [state, setState] = useState({
-    params: {
-      projectType: roadpricingEnum[columnStateType],
-      search: null
-    }
+    search: null
   })
-
+  const memoRef = useCreation(() => {
+    const columnStateType = window.location.pathname?.match(/\/([^/]*)$/)[1]?.toUpperCase()
+    const compilation = cloud.compilation[roadpricingEnum[columnStateType]]
+    const province = cloud.province[roadpricingEnum[columnStateType]]
+    return { columnStateType, compilation, province }
+  }, [window.location.pathname, cloud])
   useEffect(() => {
-    if (!compilation?.length) {
+    if (!cloud.compilation[roadpricingEnum[memoRef.columnStateType]]?.length) {
       dispatch({
         type: 'cloud/fetchCompilation',
         payload: {
-          projectType: roadpricingEnum[columnStateType]
+          projectType: roadpricingEnum[memoRef.columnStateType]
         }
       })
     }
-    if (!province?.length) {
+    if (!cloud.province[roadpricingEnum[memoRef.columnStateType]]?.length) {
       dispatch({
         type: 'cloud/fetchProvince',
         payload: {
-          projectType: roadpricingEnum[columnStateType]
+          projectType: roadpricingEnum[memoRef.columnStateType]
         }
       })
     }
-  }, [])
+  }, [memoRef.columnStateType])
 
   const columns = [
     {
@@ -67,7 +59,7 @@ const Cloud = () => {
           onClick={() =>
             dispatchModal('D_CLOUD_DETAIL', {
               dataId: record.ssoId,
-              projectType: roadpricingEnum[columnStateType]
+              projectType: roadpricingEnum[memoRef.columnStateType]
             })
           }
           className="text-primary cursor-pointer hover:text-[#967bbd]">
@@ -166,7 +158,7 @@ const Cloud = () => {
       filters: true,
       filterMultiple: false,
       width: 120,
-      valueEnum: compilation.reduce((prev, curr) => {
+      valueEnum: memoRef.compilation.reduce((prev, curr) => {
         const obj = { ...prev }
         if (curr._id) {
           obj[curr._id] = {
@@ -182,7 +174,7 @@ const Cloud = () => {
       dataIndex: 'province',
       key: 'province',
       filters: true,
-      valueEnum: province.reduce((prev, curr) => {
+      valueEnum: memoRef.province.reduce((prev, curr) => {
         const obj = { ...prev }
         obj[curr.value] = {
           text: curr.label
@@ -208,7 +200,7 @@ const Cloud = () => {
       width: 150,
       filters: true,
       filterMultiple: false,
-      valueEnum: compilation.reduce((prev, curr) => {
+      valueEnum: memoRef.compilation.reduce((prev, curr) => {
         const obj = { ...prev }
         if (curr._id) {
           obj[curr._id] = {
@@ -221,12 +213,13 @@ const Cloud = () => {
         <div className="!children:m-2px">
           {record.upgrade_list
             .filter(
-              item => item.isUpgrade && compilation?.findIndex(i => i._id === item.compilationID) !== -1
+              item =>
+                item.isUpgrade && memoRef.compilation?.findIndex(i => i._id === item.compilationID) !== -1
             )
             .map(item => {
               return (
                 <Tag color="purple" key={item.compilationID}>
-                  {compilation?.find(i => i._id === item.compilationID)?.name}
+                  {memoRef.compilation?.find(i => i._id === item.compilationID)?.name}
                 </Tag>
               )
             })}
@@ -265,13 +258,11 @@ const Cloud = () => {
       <BasicTable
         actionRef={tRef}
         rowKey={record => record._id}
-        columnStateType={columnStateType}
-        params={state.params}
+        params={{ searhc: state.search, projectType: roadpricingEnum[memoRef.columnStateType] }}
         request={async (params, sort, filter) => {
-          const sortOrder = generateSortField(sort)
           const {
             data: { list = [], total = 0 }
-          } = await queryRoadpricingList({ ...params, ...sortOrder, ...filter })
+          } = await queryRoadpricingList({ ...params, ...sort, ...filter })
           return {
             data: list,
             total
@@ -300,4 +291,6 @@ const Cloud = () => {
   )
 }
 
-export default Cloud
+export default connect(({ cloud }) => ({
+  cloud
+}))(Cloud)

+ 9 - 0
src/typings.d.ts

@@ -41,5 +41,14 @@ declare let ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: 'site' | undefine
 declare const REACT_APP_ENV: 'test' | 'dev' | 'pre' | false
 
 declare type Nullable<T> = T | null
+declare type NonNullable<T> = T extends null | undefined ? never : T
+declare type Recordable<T = any> = Record<string, T>
 
 declare type ActionPayload = { main: string; target: string }
+
+declare type ResponseStructure<T> = {
+  code: number
+  data: T
+  msg?: string
+  showType: number
+}