feat: 实现统一错误处理系统 (003-error-handling)

- 新增统一错误码定义和管理 (pkg/errors/codes.go)
- 新增全局错误处理器和中间件 (pkg/errors/handler.go, internal/middleware/error_handler.go)
- 新增错误上下文管理 (pkg/errors/context.go)
- 增强 Panic 恢复中间件 (internal/middleware/recover.go)
- 新增完整的单元测试和集成测试
- 新增功能文档 (docs/003-error-handling/)
- 新增功能规范 (specs/003-error-handling/)
- 更新 CLAUDE.md 和 README.md
This commit is contained in:
2025-11-15 12:17:44 +08:00
parent a371f1cd21
commit fb83c9a706
33 changed files with 7373 additions and 52 deletions

View File

@@ -15,9 +15,10 @@ var (
// AppError 表示带错误码的应用错误
type AppError struct {
Code int // 应用错误码
Message string // 错误消息
Err error // 底层错误(可选
Code int // 应用错误码
Message string // 错误消息
HTTPStatus int // HTTP 状态码(自动从 Code 映射,可通过 WithHTTPStatus 覆盖
Err error // 底层错误(可选)
}
func (e *AppError) Error() string {
@@ -33,17 +34,33 @@ func (e *AppError) Unwrap() error {
// New 创建新的 AppError
func New(code int, message string) *AppError {
// 如果消息为空,使用默认消息
if message == "" {
message = GetMessage(code, "zh-CN")
}
return &AppError{
Code: code,
Message: message,
Code: code,
Message: message,
HTTPStatus: GetHTTPStatus(code), // 自动从错误码映射 HTTP 状态码
}
}
// Wrap 用错误码和消息包装现有错误
func Wrap(code int, message string, err error) *AppError {
// 如果消息为空,使用默认消息
if message == "" {
message = GetMessage(code, "zh-CN")
}
return &AppError{
Code: code,
Message: message,
Err: err,
Code: code,
Message: message,
HTTPStatus: GetHTTPStatus(code), // 自动从错误码映射 HTTP 状态码
Err: err,
}
}
// WithHTTPStatus 设置自定义 HTTP 状态码(用于特殊场景)
func (e *AppError) WithHTTPStatus(status int) *AppError {
e.HTTPStatus = status
return e
}