名称: api-error-handling 描述: 实现标准化的API错误响应,包含正确的状态码、日志记录和用户友好的消息。用于构建生产API、实现错误恢复模式或集成错误监控服务时使用。
API 错误处理
实现健壮的错误处理,包含标准化响应和适当的日志记录。
标准错误响应格式
{
"error": {
"code": "VALIDATION_ERROR",
"message": "请求参数无效",
"status": 400,
"requestId": "req_abc123",
"timestamp": "2025-01-15T10:30:00Z",
"details": [
{ "field": "email", "message": "电子邮件格式无效" }
]
}
}
错误类 (Node.js)
class ApiError extends Error {
constructor(code, message, status = 500, details = null) {
super(message);
this.code = code;
this.status = status;
this.details = details;
}
static badRequest(message, details) {
return new ApiError('BAD_REQUEST', message, 400, details);
}
static notFound(resource) {
return new ApiError('NOT_FOUND', `${resource} 未找到`, 404);
}
static unauthorized() {
return new ApiError('UNAUTHORIZED', '需要认证', 401);
}
}
// 全局错误处理器
app.use((err, req, res, next) => {
const status = err.status || 500;
const response = {
error: {
code: err.code || 'INTERNAL_ERROR',
message: status === 500 ? '内部服务器错误' : err.message,
status,
requestId: req.id
}
};
if (err.details) response.error.details = err.details;
if (status >= 500) logger.error(err);
res.status(status).json(response);
});
断路器模式
class CircuitBreaker {
constructor(threshold = 5, timeout = 30000) {
this.failures = 0;
this.threshold = threshold;
this.timeout = timeout;
this.state = 'CLOSED';
}
async call(fn) {
if (this.state === 'OPEN') throw new Error('断路器打开');
try {
const result = await fn();
this.failures = 0;
return result;
} catch (err) {
this.failures++;
if (this.failures >= this.threshold) {
this.state = 'OPEN';
setTimeout(() => this.state = 'HALF_OPEN', this.timeout);
}
throw err;
}
}
}
附加实现
参见 references/python-flask.md 了解:
- Python Flask 错误处理与自定义异常
- 断路器与自动恢复
- 指数退避重试
- Sentry 集成
最佳实践
- 在所有端点使用一致的错误格式
- 包含请求ID以便追踪
- 在适当严重级别记录错误
- 切勿向客户端暴露堆栈跟踪
- 区分客户端错误 (4xx) 和服务器错误 (5xx)
- 提供可操作的错误消息