Skip to content

Commit b0e51ed

Browse files
author
feige996
committed
refactor(http): 修改请求返回类型并处理业务逻辑错误
移除 IResData 包装层,直接返回数据部分。在 http 模块中添加业务逻辑错误处理,当 code 不为成功时抛出错误
1 parent 1b9723e commit b0e51ed

2 files changed

Lines changed: 11 additions & 6 deletions

File tree

src/hooks/useRequest.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ interface IUseRequestReturn<T> {
2323
* @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。
2424
*/
2525
export default function useRequest<T>(
26-
func: () => Promise<IResData<T>>,
26+
func: () => Promise<T>,
2727
options: IUseRequestOptions<T> = { immediate: false },
2828
): IUseRequestReturn<T> {
2929
const loading = ref(false)
@@ -33,7 +33,7 @@ export default function useRequest<T>(
3333
loading.value = true
3434
return func()
3535
.then((res) => {
36-
data.value = res.data
36+
data.value = res
3737
error.value = false
3838
return data.value
3939
})

src/http/http.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
import type { IDoubleTokenRes } from '@/api/types/login'
2-
import type { CustomRequestOptions } from '@/http/types'
2+
import type { CustomRequestOptions, IResponse } from '@/http/types'
33
import { nextTick } from 'vue'
44
import { LOGIN_PAGE } from '@/router/config'
55
import { useTokenStore } from '@/store/token'
66
import { isDoubleTokenMode } from '@/utils'
7+
import { ResultEnum } from './tools/enum'
78

89
// 刷新 token 状态管理
910
let refreshing = false // 防止重复刷新 token 标识
1011
let taskQueue: (() => void)[] = [] // 刷新 token 请求队列
1112

1213
export function http<T>(options: CustomRequestOptions) {
1314
// 1. 返回 Promise 对象
14-
return new Promise<IResData<T>>((resolve, reject) => {
15+
return new Promise<T>((resolve, reject) => {
1516
uni.request({
1617
...options,
1718
dataType: 'json',
@@ -22,8 +23,12 @@ export function http<T>(options: CustomRequestOptions) {
2223
success: async (res) => {
2324
// 状态码 2xx,参考 axios 的设计
2425
if (res.statusCode >= 200 && res.statusCode < 300) {
25-
// 2.1 提取核心数据 res.data
26-
return resolve(res.data as IResData<T>)
26+
// 2.1 处理业务逻辑错误
27+
const { code, message, data } = res.data as IResponse<T>
28+
if (code !== ResultEnum.Success) {
29+
throw new Error(`请求错误[${code}]:${message}`)
30+
}
31+
return resolve(data as T)
2732
}
2833
const resData: IResData<T> = res.data as IResData<T>
2934
if ((res.statusCode === 401) || (resData.code === 401)) {

0 commit comments

Comments
 (0)