Files
langx/error.go
T

62 lines
1.1 KiB
Go
Raw Normal View History

2024-06-30 11:52:34 +08:00
package langx
import (
"context"
)
2024-11-10 22:55:35 +08:00
// Key生成错误信息
2024-07-24 19:47:00 +08:00
type LangError interface {
2024-11-10 22:28:02 +08:00
Error() string // 实现error接口&获取翻译后的错误信息
GetCode() int // 获取翻译后的Code
GetKey() string // 获取原Key值
GetFormat() map[string]string // 获取附加数据
SetLang(lang string) // 设置语言
2024-07-24 19:47:00 +08:00
}
2024-11-10 22:55:35 +08:00
2024-07-24 19:47:00 +08:00
type langError struct {
2024-06-30 11:52:34 +08:00
ctx context.Context
key string
format map[string]string
}
2024-11-10 22:28:02 +08:00
func (l *langError) Error() string {
return GetFormat(GetCtxLang(l.ctx), l.key, l.format)
2024-06-30 11:52:34 +08:00
}
2024-07-24 19:47:00 +08:00
func (e *langError) GetCode() int {
2024-06-30 11:52:34 +08:00
return GetCode(e.key)
}
2024-07-31 16:47:23 +08:00
func (e *langError) GetKey() string {
2024-07-10 18:45:55 +08:00
return e.key
}
2024-07-24 19:47:00 +08:00
func (e *langError) GetFormat() map[string]string {
2024-07-10 18:45:55 +08:00
if e.format == nil {
e.format = make(map[string]string)
}
return e.format
}
2024-11-10 22:28:02 +08:00
func (e *langError) SetLang(lang string) {
e.ctx = SetCtxLang(e.ctx, lang)
}
func NewErrorf(ctx context.Context, key string, format map[string]string) error {
2024-07-24 19:47:00 +08:00
return &langError{
2024-06-30 11:52:34 +08:00
ctx: ctx,
key: key,
format: format,
}
}
func NewError(ctx context.Context, key string) error {
2024-07-24 19:47:00 +08:00
return &langError{
2024-06-30 11:52:34 +08:00
ctx: ctx,
key: key,
}
}