From b0e51ed39f91dcc1556e5b8df819afcbfe411a98 Mon Sep 17 00:00:00 2001 From: feige996 <1020102647@qq.com> Date: Sun, 14 Sep 2025 21:02:32 +0800 Subject: [PATCH] =?UTF-8?q?refactor(http):=20=E4=BF=AE=E6=94=B9=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E8=BF=94=E5=9B=9E=E7=B1=BB=E5=9E=8B=E5=B9=B6=E5=A4=84?= =?UTF-8?q?=E7=90=86=E4=B8=9A=E5=8A=A1=E9=80=BB=E8=BE=91=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 移除 IResData 包装层,直接返回数据部分。在 http 模块中添加业务逻辑错误处理,当 code 不为成功时抛出错误 --- src/hooks/useRequest.ts | 4 ++-- src/http/http.ts | 13 +++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/hooks/useRequest.ts b/src/hooks/useRequest.ts index 017a710..62156d7 100644 --- a/src/hooks/useRequest.ts +++ b/src/hooks/useRequest.ts @@ -23,7 +23,7 @@ interface IUseRequestReturn { * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。 */ export default function useRequest( - func: () => Promise>, + func: () => Promise, options: IUseRequestOptions = { immediate: false }, ): IUseRequestReturn { const loading = ref(false) @@ -33,7 +33,7 @@ export default function useRequest( loading.value = true return func() .then((res) => { - data.value = res.data + data.value = res error.value = false return data.value }) diff --git a/src/http/http.ts b/src/http/http.ts index 1d3ce2e..fac0dca 100644 --- a/src/http/http.ts +++ b/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(options: CustomRequestOptions) { // 1. 返回 Promise 对象 - return new Promise>((resolve, reject) => { + return new Promise((resolve, reject) => { uni.request({ ...options, dataType: 'json', @@ -22,8 +23,12 @@ export function http(options: CustomRequestOptions) { success: async (res) => { // 状态码 2xx,参考 axios 的设计 if (res.statusCode >= 200 && res.statusCode < 300) { - // 2.1 提取核心数据 res.data - return resolve(res.data as IResData) + // 2.1 处理业务逻辑错误 + const { code, message, data } = res.data as IResponse + if (code !== ResultEnum.Success) { + throw new Error(`请求错误[${code}]:${message}`) + } + return resolve(data as T) } const resData: IResData = res.data as IResData if ((res.statusCode === 401) || (resData.code === 401)) {