46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
|
|
import type { AxiosResponse } from 'axios';
|
|||
|
|
import { emitEvent } from '@/utils/eventBus';
|
|||
|
|
export interface ReqReturn<T>{
|
|||
|
|
data:AxiosResponse<T> | T |null;
|
|||
|
|
error:any;
|
|||
|
|
}
|
|||
|
|
type ReqFn<T = any, D = any> = (params: D) => Promise<AxiosResponse<T> | T>;
|
|||
|
|
type ReqFnSelect<T = any, D = any> = (params?: D) => Promise<AxiosResponse<T> | T>;
|
|||
|
|
export async function reqCatch<T = any, D = any>(req: ReqFn<T, D> | ReqFnSelect<T, D>, params?: D):
|
|||
|
|
Promise<ReqReturn<T>> {
|
|||
|
|
try {
|
|||
|
|
const data = await req(params);
|
|||
|
|
return {
|
|||
|
|
data,
|
|||
|
|
error: null
|
|||
|
|
};
|
|||
|
|
} catch (e) {
|
|||
|
|
// 可在此处定义全局的错误处理方法,也可在外部处理
|
|||
|
|
return {
|
|||
|
|
data: null,
|
|||
|
|
error: e
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
interface ReqReturnV2<T>{
|
|||
|
|
data:AxiosResponse<T>|null;
|
|||
|
|
error:any;
|
|||
|
|
}
|
|||
|
|
export type catchRt<T> = Promise<ReqReturnV2<T>>;
|
|||
|
|
export async function reqCatchV2<R=any>(req:()=>Promise<AxiosResponse<R>>):catchRt<R> { // 设置请求函数的返回值,R类型可以自动推导
|
|||
|
|
try {
|
|||
|
|
const data = await req();
|
|||
|
|
return {
|
|||
|
|
data,
|
|||
|
|
error: null
|
|||
|
|
};
|
|||
|
|
} catch (e) {
|
|||
|
|
// 可在此处定义全局的错误处理方法,也可在外部处理
|
|||
|
|
emitEvent('responseError', e);
|
|||
|
|
return {
|
|||
|
|
data: null,
|
|||
|
|
error: e
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
}
|