Files
junhong_cmp_fiber/pkg/errors/errors.go
huang 6821e5abcf
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m36s
refactor: 统一错误消息数据源,优化错误码与映射表管理
主要改动:
- 改造 errors.New() 和 Wrap() 函数签名为可变参数,优先使用 errorMessages 映射表
- 添加 allErrorCodes 注册表和 init() 启动时校验,确保错误码与映射表一致
- 添加 TestAllCodesHaveMessages 和 TestNoOrphanMessages 测试防止映射表腐化
- 清理 109 处与映射表一致的冗余硬编码(service 层)
- 保留业务特定消息覆盖能力

新增 API 用法:
- errors.New(errors.CodeUnauthorized) // 使用映射表默认消息
- errors.New(errors.CodeNotFound, "提现申请不存在") // 覆盖为自定义消息
2026-01-22 18:27:42 +08:00

68 lines
1.9 KiB
Go

package errors
import (
"errors"
"fmt"
)
// 中间件标准错误类型
var (
ErrMissingToken = errors.New("missing authentication token")
ErrInvalidToken = errors.New("invalid or expired token")
ErrRedisUnavailable = errors.New("redis unavailable")
ErrTooManyRequests = errors.New("too many requests")
)
// AppError 表示带错误码的应用错误
type AppError struct {
Code int // 应用错误码
Message string // 错误消息
Err error // 底层错误(可选)
}
func (e *AppError) Error() string {
if e.Err != nil {
return fmt.Sprintf("%s: %v", e.Message, e.Err)
}
return e.Message
}
func (e *AppError) Unwrap() error {
return e.Err
}
// New 创建新的 AppError
// 优先使用 errorMessages 映射表中的消息,允许通过可选参数覆盖
// 用法:
// - errors.New(errors.CodeNotFound) // 使用映射表默认消息
// - errors.New(errors.CodeNotFound, "提现申请不存在") // 覆盖为自定义消息
func New(code int, customMsg ...string) *AppError {
// 默认从映射表获取消息
message := GetMessage(code, "zh-CN")
// 如果提供了自定义消息且非空,则覆盖
if len(customMsg) > 0 && customMsg[0] != "" {
message = customMsg[0]
}
return &AppError{
Code: code,
Message: message,
}
}
// Wrap 用错误码和消息包装现有错误
// 优先使用 errorMessages 映射表中的消息,允许通过可选参数覆盖
// 用法:
// - errors.Wrap(errors.CodeDatabaseError, originalErr) // 使用映射表默认消息
// - errors.Wrap(errors.CodeDatabaseError, originalErr, "查询用户失败") // 覆盖为自定义消息
func Wrap(code int, err error, customMsg ...string) *AppError {
message := GetMessage(code, "zh-CN")
if len(customMsg) > 0 && customMsg[0] != "" {
message = customMsg[0]
}
return &AppError{
Code: code,
Message: message,
Err: err,
}
}