/** * API 错误类,用于封装 API 请求错误 */ export class ApiError extends Error { status: number; constructor(message: string, status: number = 500) { super(message); this.name = 'ApiError'; this.status = status; } } /** * 处理 API 错误 * @param error 捕获的错误对象 * @returns 统一的 ApiError 对象 */ export function handleApiError(error: unknown): ApiError { if (error instanceof ApiError) { return error; } if (error instanceof Error) { return new ApiError(error.message); } return new ApiError('未知错误'); } /** * 创建一个标准的错误响应 * @param message 错误消息 * @param status HTTP 状态码 */ export function createErrorResponse(message: string, status: number = 400): Response { return new Response( JSON.stringify({ error: message }), { status, headers: { 'Content-Type': 'application/json' } } ); }