做完了一部分,备份一下,防止以外删除
This commit is contained in:
39
pkg/errors/codes.go
Normal file
39
pkg/errors/codes.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package errors
|
||||
|
||||
// 应用错误码
|
||||
const (
|
||||
CodeSuccess = 0 // 成功
|
||||
CodeInternalError = 1000 // 内部服务器错误
|
||||
CodeMissingToken = 1001 // 缺失认证令牌
|
||||
CodeInvalidToken = 1002 // 令牌无效或已过期
|
||||
CodeTooManyRequests = 1003 // 请求过于频繁(限流)
|
||||
CodeAuthServiceUnavailable = 1004 // 认证服务不可用(Redis 宕机)
|
||||
)
|
||||
|
||||
// ErrorMessage 表示双语错误消息
|
||||
type ErrorMessage struct {
|
||||
EN string
|
||||
ZH string
|
||||
}
|
||||
|
||||
// errorMessages 将错误码映射到双语消息
|
||||
var errorMessages = map[int]ErrorMessage{
|
||||
CodeSuccess: {"Success", "成功"},
|
||||
CodeInternalError: {"Internal server error", "内部服务器错误"},
|
||||
CodeMissingToken: {"Missing authentication token", "缺失认证令牌"},
|
||||
CodeInvalidToken: {"Invalid or expired token", "令牌无效或已过期"},
|
||||
CodeTooManyRequests: {"Too many requests", "请求过于频繁"},
|
||||
CodeAuthServiceUnavailable: {"Authentication service unavailable", "认证服务不可用"},
|
||||
}
|
||||
|
||||
// GetMessage 根据错误码和语言返回错误消息
|
||||
func GetMessage(code int, lang string) string {
|
||||
msg, ok := errorMessages[code]
|
||||
if !ok {
|
||||
return "Unknown error"
|
||||
}
|
||||
if lang == "zh" || lang == "zh-CN" {
|
||||
return msg.ZH
|
||||
}
|
||||
return msg.EN
|
||||
}
|
||||
49
pkg/errors/errors.go
Normal file
49
pkg/errors/errors.go
Normal file
@@ -0,0 +1,49 @@
|
||||
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
|
||||
func New(code int, message string) *AppError {
|
||||
return &AppError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap 用错误码和消息包装现有错误
|
||||
func Wrap(code int, message string, err error) *AppError {
|
||||
return &AppError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user