Files
langx/consts.go
T

59 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-11-10 22:55:35 +08:00
package langx
import "context"
// 定义错误常量
2025-10-26 15:41:30 +08:00
type ErrorLanguage struct {
LangError
}
2024-11-10 22:55:35 +08:00
// 生成错误常量
func NewLanguage(uniKey string, code int, defaultValue string) ErrorLanguage {
AppendCode(map[string]int{uniKey: code})
2025-10-26 15:41:30 +08:00
AppendTrans(GetDefaultLang(), map[string]string{uniKey: defaultValue})
2024-11-10 22:55:35 +08:00
2025-10-26 15:52:32 +08:00
l := NewStruct(context.Background(), uniKey, nil)
2025-10-26 15:41:30 +08:00
return ErrorLanguage{l}
2024-11-10 22:55:35 +08:00
}
// Key生成错误信息
func (l ErrorLanguage) Err() error {
2025-10-26 15:41:30 +08:00
return l
2024-11-10 22:55:35 +08:00
}
// Key生成错误信息
func (l ErrorLanguage) Errf(format map[string]string) error {
2025-10-26 15:41:30 +08:00
newLang := l.Copy()
newLang.SetFormat(format)
return newLang
2024-11-10 22:55:35 +08:00
}
2025-10-26 15:41:30 +08:00
func (l ErrorLanguage) ErrfKV(key, value string) error {
newLang := l.Copy()
newLang.SetFormatKV(key, value)
return newLang
2024-11-10 22:55:35 +08:00
}
// 获取翻译后的错误信息
func (l ErrorLanguage) Msg(ctx context.Context) string {
2025-10-26 15:41:30 +08:00
newLang := l.Copy()
newLang.SetCtx(ctx)
return newLang.Error()
2024-11-10 22:55:35 +08:00
}
// 获取翻译后的错误信息
func (l ErrorLanguage) Msgf(ctx context.Context, format map[string]string) string {
2025-10-26 15:41:30 +08:00
newLang := l.Copy()
newLang.SetCtx(ctx)
newLang.SetFormat(format)
return newLang.Error()
2024-11-10 22:55:35 +08:00
}
var (
Success ErrorLanguage = NewLanguage("success", 200, "操作成功")
Error ErrorLanguage = NewLanguage("error", 400, "操作失败")
ErrWithMsg ErrorLanguage = NewLanguage("error_with_msg", 400, "操作失败: #msg#")
)