/** * 错误处理中间件 */ import { Request, Response, NextFunction } from 'express'; export function errorHandler( err: Error, req: Request, res: Response, next: NextFunction ): void { console.error('[Error]', err.message, err.stack); // 根据错误类型返回不同状态码 const status = (err as any).status || 500; res.status(status).json({ error: err.name || 'InternalError', message: err.message, timestamp: Date.now(), }); } // 异步错误捕获包装器 export function asyncHandler(fn: (req: Request, res: Response, next: NextFunction) => Promise) { return (req: Request, res: Response, next: NextFunction) => { Promise.resolve(fn(req, res, next)).catch(next); }; }