优化逻辑
This commit is contained in:
@@ -5,10 +5,11 @@ import (
|
||||
)
|
||||
|
||||
type LangError interface {
|
||||
Error() string // 实现error接口&获取翻译后的错误信息
|
||||
GetCode() int // 获取翻译后的Code
|
||||
GetKey() string // 获取原Key值
|
||||
GetFormat() map[string]string // 获取附加数据
|
||||
Error() string // 实现error接口&获取翻译后的错误信息
|
||||
GetCode() int // 获取翻译后的Code
|
||||
GetKey() string // 获取原Key值
|
||||
GetFormat() map[string]string // 获取附加数据
|
||||
SetLang(lang string) // 设置语言
|
||||
}
|
||||
|
||||
type langError struct {
|
||||
@@ -17,15 +18,8 @@ type langError struct {
|
||||
format map[string]string
|
||||
}
|
||||
|
||||
type errorConst string
|
||||
|
||||
func (e *langError) Error() string {
|
||||
errLang := e.ctx.Value(errorLang)
|
||||
l := ""
|
||||
if errLang != nil {
|
||||
l = string(errLang.(errorConst))
|
||||
}
|
||||
return GetFormat(l, e.key, e.format)
|
||||
func (l *langError) Error() string {
|
||||
return GetFormat(GetCtxLang(l.ctx), l.key, l.format)
|
||||
}
|
||||
|
||||
func (e *langError) GetCode() int {
|
||||
@@ -43,7 +37,11 @@ func (e *langError) GetFormat() map[string]string {
|
||||
return e.format
|
||||
}
|
||||
|
||||
func NewErrorFormat(ctx context.Context, key string, format map[string]string) error {
|
||||
func (e *langError) SetLang(lang string) {
|
||||
e.ctx = SetCtxLang(e.ctx, lang)
|
||||
}
|
||||
|
||||
func NewErrorf(ctx context.Context, key string, format map[string]string) error {
|
||||
return &langError{
|
||||
ctx: ctx,
|
||||
key: key,
|
||||
@@ -57,9 +55,3 @@ func NewError(ctx context.Context, key string) error {
|
||||
key: key,
|
||||
}
|
||||
}
|
||||
|
||||
const errorLang errorConst = "errorLang"
|
||||
|
||||
func SetCtxLang(ctx context.Context, lang string) context.Context {
|
||||
return context.WithValue(ctx, errorLang, lang)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user