Sfoglia il codice sorgente

refactor(http): 修改请求返回类型并处理业务逻辑错误

移除 IResData 包装层,直接返回数据部分。在 http 模块中添加业务逻辑错误处理,当 code 不为成功时抛出错误
feige996 7 mesi fa
parent
commit
b0e51ed39f
2 ha cambiato i file con 11 aggiunte e 6 eliminazioni
  1. 2 2
      src/hooks/useRequest.ts
  2. 9 4
      src/http/http.ts

+ 2 - 2
src/hooks/useRequest.ts

@@ -23,7 +23,7 @@ interface IUseRequestReturn<T> {
  * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
  */
 export default function useRequest<T>(
-  func: () => Promise<IResData<T>>,
+  func: () => Promise<T>,
   options: IUseRequestOptions<T> = { immediate: false },
 ): IUseRequestReturn<T> {
   const loading = ref(false)
@@ -33,7 +33,7 @@ export default function useRequest<T>(
     loading.value = true
     return func()
       .then((res) => {
-        data.value = res.data
+        data.value = res
         error.value = false
         return data.value
       })

+ 9 - 4
src/http/http.ts

@@ -1,9 +1,10 @@
 import type { IDoubleTokenRes } from '@/api/types/login'
-import type { CustomRequestOptions } from '@/http/types'
+import type { CustomRequestOptions, IResponse } from '@/http/types'
 import { nextTick } from 'vue'
 import { LOGIN_PAGE } from '@/router/config'
 import { useTokenStore } from '@/store/token'
 import { isDoubleTokenMode } from '@/utils'
+import { ResultEnum } from './tools/enum'
 
 // 刷新 token 状态管理
 let refreshing = false // 防止重复刷新 token 标识
@@ -11,7 +12,7 @@ let taskQueue: (() => void)[] = [] // 刷新 token 请求队列
 
 export function http<T>(options: CustomRequestOptions) {
   // 1. 返回 Promise 对象
-  return new Promise<IResData<T>>((resolve, reject) => {
+  return new Promise<T>((resolve, reject) => {
     uni.request({
       ...options,
       dataType: 'json',
@@ -22,8 +23,12 @@ export function http<T>(options: CustomRequestOptions) {
       success: async (res) => {
         // 状态码 2xx,参考 axios 的设计
         if (res.statusCode >= 200 && res.statusCode < 300) {
-          // 2.1 提取核心数据 res.data
-          return resolve(res.data as IResData<T>)
+          // 2.1  处理业务逻辑错误
+          const { code, message, data } = res.data as IResponse<T>
+          if (code !== ResultEnum.Success) {
+            throw new Error(`请求错误[${code}]:${message}`)
+          }
+          return resolve(data as T)
         }
         const resData: IResData<T> = res.data as IResData<T>
         if ((res.statusCode === 401) || (resData.code === 401)) {