完善错误码的用法

This commit is contained in:
yun
2026-07-22 00:05:37 +08:00
parent 8eaa8a6933
commit 4e81b83ab6
6 changed files with 620 additions and 211 deletions
+58 -62
View File
@@ -1,62 +1,58 @@
package errorx
import (
"context"
"github.com/yuninks/langx"
)
// 定义错误常量
type ErrorLanguage struct {
ErrorInterface
}
// 生成错误常量
func NewLanguage(uniKey string, code int, defaultValue string) ErrorLanguage {
langx.AppendCode(map[string]int{uniKey: code})
langx.AppendTrans(langx.GetDefaultLang(), map[string]string{uniKey: defaultValue})
l := NewStruct(context.Background(), uniKey, nil)
return ErrorLanguage{l}
}
// Key生成错误信息
func (l ErrorLanguage) Err() error {
return l
}
// Key生成错误信息
func (l ErrorLanguage) Errf(format map[string]string) error {
newLang := l.Copy()
newLang.SetFormat(format)
return newLang
}
func (l ErrorLanguage) ErrfKV(key, value string) error {
newLang := l.Copy()
newLang.SetFormatKV(key, value)
return newLang
}
// 获取翻译后的错误信息
func (l ErrorLanguage) Msg(ctx context.Context) string {
newLang := l.Copy()
newLang.SetCtx(ctx)
return newLang.Error()
}
// 获取翻译后的错误信息
func (l ErrorLanguage) Msgf(ctx context.Context, format map[string]string) string {
newLang := l.Copy()
newLang.SetCtx(ctx)
newLang.SetFormat(format)
return newLang.Error()
}
var (
Success ErrorLanguage = NewLanguage("success", 200, "操作成功")
Error ErrorLanguage = NewLanguage("error", 400, "操作失败")
ErrWithMsg ErrorLanguage = NewLanguage("error_with_msg", 400, "操作失败: #msg#")
)
package errorx
import (
"context"
"github.com/yuninks/langx"
)
// ErrorCode 表示一个预定义错误码,是纯值类型,无状态、并发安全。
// 声明为 var 后不会被意外修改。
type ErrorCode struct {
key string
code int
}
// NewCode 创建一个错误码,并自动注册到 langx 全局表中。
// - key: 唯一标识符
// - code: 业务错误码
// - defaultMsg: 默认语言下的消息模板
func NewCode(key string, code int, defaultMsg string) ErrorCode {
langx.AppendCode(map[string]int{key: code})
langx.AppendTrans(langx.GetDefaultLang(), map[string]string{key: defaultMsg})
return ErrorCode{key: key, code: code}
}
// Key 返回唯一标识符。
func (ec ErrorCode) Key() string { return ec.key }
// Code 返回业务错误码。
func (ec ErrorCode) Code() int { return ec.code }
// New 创建一个携带上下文的运行时错误。
func (ec ErrorCode) New(ctx context.Context) *langError {
return NewError(ctx, ec.key)
}
// Newf 创建一个携带占位符键值对的运行时错误。
func (ec ErrorCode) Newf(ctx context.Context, kv map[string]string) *langError {
return NewErrorf(ctx, ec.key, kv)
}
// Msg 直接获取当前上下文语言下的翻译消息。
func (ec ErrorCode) Msg(ctx context.Context) string {
return langx.GetFormat(langx.GetCtxLang(ctx), ec.key, nil)
}
// Msgf 直接获取带占位符替换的翻译消息。
func (ec ErrorCode) Msgf(ctx context.Context, kv map[string]string) string {
return langx.GetFormat(langx.GetCtxLang(ctx), ec.key, kv)
}
// ---- 预定义错误码 ----------------------------------------------------
var (
Success = NewCode("success", 200, "操作成功")
Error = NewCode("error", 400, "操作失败")
ErrWithMsg = NewCode("error_with_msg", 400, "操作失败: #msg#")
)