refactor: 统一错误消息数据源,优化错误码与映射表管理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m36s
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m36s
主要改动: - 改造 errors.New() 和 Wrap() 函数签名为可变参数,优先使用 errorMessages 映射表 - 添加 allErrorCodes 注册表和 init() 启动时校验,确保错误码与映射表一致 - 添加 TestAllCodesHaveMessages 和 TestNoOrphanMessages 测试防止映射表腐化 - 清理 109 处与映射表一致的冗余硬编码(service 层) - 保留业务特定消息覆盖能力 新增 API 用法: - errors.New(errors.CodeUnauthorized) // 使用映射表默认消息 - errors.New(errors.CodeNotFound, "提现申请不存在") // 覆盖为自定义消息
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package errors
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 错误码定义
|
||||
const (
|
||||
// 成功
|
||||
@@ -66,6 +68,68 @@ const (
|
||||
CodeTaskQueueError = 2006 // 任务队列错误
|
||||
)
|
||||
|
||||
// allErrorCodes 所有已注册的错误码
|
||||
// 新增错误码时必须同时在此列表中注册
|
||||
var allErrorCodes = []int{
|
||||
CodeSuccess,
|
||||
CodeInvalidParam,
|
||||
CodeMissingToken,
|
||||
CodeInvalidToken,
|
||||
CodeUnauthorized,
|
||||
CodeForbidden,
|
||||
CodeNotFound,
|
||||
CodeConflict,
|
||||
CodeTooManyRequests,
|
||||
CodeRequestTooLarge,
|
||||
CodeAccountNotFound,
|
||||
CodeAccountDisabled,
|
||||
CodeAccountDeleted,
|
||||
CodeUsernameExists,
|
||||
CodePhoneExists,
|
||||
CodeInvalidPassword,
|
||||
CodePasswordTooWeak,
|
||||
CodeParentIDRequired,
|
||||
CodeInvalidParentID,
|
||||
CodeCannotModifyParent,
|
||||
CodeCannotModifyUserType,
|
||||
CodeRoleNotFound,
|
||||
CodeRoleNameExists,
|
||||
CodePermissionNotFound,
|
||||
CodePermCodeExists,
|
||||
CodeInvalidPermCode,
|
||||
CodeRoleAlreadyAssigned,
|
||||
CodePermAlreadyAssigned,
|
||||
CodeShopNotFound,
|
||||
CodeShopCodeExists,
|
||||
CodeShopLevelExceeded,
|
||||
CodeEnterpriseNotFound,
|
||||
CodeEnterpriseCodeExists,
|
||||
CodeCustomerNotFound,
|
||||
CodeCustomerPhoneExists,
|
||||
CodeInvalidCredentials,
|
||||
CodeAccountLocked,
|
||||
CodePasswordExpired,
|
||||
CodeInvalidOldPassword,
|
||||
CodeInvalidStatus,
|
||||
CodeInsufficientBalance,
|
||||
CodeWithdrawalNotFound,
|
||||
CodeWalletNotFound,
|
||||
CodeInternalError,
|
||||
CodeDatabaseError,
|
||||
CodeRedisError,
|
||||
CodeServiceUnavailable,
|
||||
CodeTimeout,
|
||||
CodeTaskQueueError,
|
||||
}
|
||||
|
||||
func init() {
|
||||
for _, code := range allErrorCodes {
|
||||
if _, ok := errorMessages[code]; !ok {
|
||||
panic(fmt.Sprintf("错误码 %d 缺少映射消息,请在 errorMessages 中添加", code))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// errorMessages 错误消息映射表(中文)
|
||||
var errorMessages = map[int]string{
|
||||
CodeSuccess: "成功",
|
||||
|
||||
Reference in New Issue
Block a user