Files
Situation-Awareness-Platfor…/src/utils/catch.ts
2025-03-12 18:41:20 +08:00

46 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
};
}
}