2024-06-30 11:52:34 +08:00
|
|
|
package langx
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type LangError struct {
|
|
|
|
|
ctx context.Context
|
|
|
|
|
key string
|
|
|
|
|
format map[string]string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type errorConst string
|
|
|
|
|
|
|
|
|
|
const errorLang errorConst = "errorLang"
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-10 18:45:55 +08:00
|
|
|
func (e *LangError) GetCode() int {
|
2024-06-30 11:52:34 +08:00
|
|
|
return GetCode(e.key)
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-10 18:45:55 +08:00
|
|
|
func (e *LangError) GetMsg() string {
|
|
|
|
|
return e.key
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (e *LangError) GetFormat() map[string]string {
|
|
|
|
|
if e.format == nil {
|
|
|
|
|
e.format = make(map[string]string)
|
|
|
|
|
}
|
|
|
|
|
return e.format
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-30 11:52:34 +08:00
|
|
|
func NewErrorFormat(ctx context.Context, key string, format map[string]string) error {
|
|
|
|
|
return &LangError{
|
|
|
|
|
ctx: ctx,
|
|
|
|
|
key: key,
|
|
|
|
|
format: format,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewError(ctx context.Context, key string) error {
|
|
|
|
|
return &LangError{
|
|
|
|
|
ctx: ctx,
|
|
|
|
|
key: key,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func SetCtxLang(ctx context.Context, lang string) context.Context {
|
|
|
|
|
return context.WithValue(ctx, errorLang, lang)
|
|
|
|
|
}
|