feat: 重构前端api封装结构
This commit is contained in:
67
apps/frontend/lib/api/common.ts
Normal file
67
apps/frontend/lib/api/common.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
||||
|
||||
export interface APIResponse<T = unknown> {
|
||||
success: boolean;
|
||||
code: number;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
export class APIError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number = 400,
|
||||
public code: number = -1,
|
||||
public data: unknown = null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeAPIError(error: unknown): never {
|
||||
if (error instanceof APIError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
throw new APIError(
|
||||
error.message || '未知错误',
|
||||
400,
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
const { message, status, code, data } = {
|
||||
message: '未知错误',
|
||||
status: 400,
|
||||
code: -1,
|
||||
data: null,
|
||||
...error
|
||||
};
|
||||
|
||||
throw new APIError(
|
||||
message,
|
||||
status,
|
||||
code,
|
||||
data
|
||||
);
|
||||
}
|
||||
|
||||
throw new APIError((error instanceof Error ? `${error.message}` : '') || '未知错误', 400);
|
||||
}
|
||||
|
||||
export function handleAPIError(error: unknown, handler: (e: APIError) => void): void {
|
||||
if (error instanceof APIError) {
|
||||
return handler(error);
|
||||
}
|
||||
|
||||
try {
|
||||
normalizeAPIError(error)
|
||||
} catch (error) {
|
||||
if (error instanceof APIError) {
|
||||
return handler(error);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user