Files
langx/error.go
T

96 lines
2.0 KiB
Go
Raw Permalink 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 {
2025-10-26 15:41:30 +08:00
Copy() LangError // 复制一个新的错误信息
2025-08-22 14:23:30 +08:00
Error() string // 实现error接口&获取翻译后的错误信息
GetCode() int // 获取翻译后的Code
GetKey() string // 获取原Key值
GetFormat() map[string]string // 获取附加数据
SetFormat(format map[string]string) // 设置附加数据
2025-10-26 15:41:30 +08:00
SetCtx(ctxHttp context.Context) // 设置上下文
SetLang(lang string) // 设置语言
SetFormatKV(key, value string) // 设置附加数据键值对
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
}
2025-08-22 14:23:30 +08:00
func (l *langError) Copy() LangError {
return &langError{
ctx: l.ctx,
key: l.key,
format: l.format,
}
}
2024-06-30 11:52:34 +08:00
2025-10-26 15:41:30 +08:00
func (e *langError) SetFormat(format map[string]string) {
e.format = format
}
func (l *langError) SetFormatKV(key, value string) {
if l.format == nil {
l.format = make(map[string]string)
2024-06-30 11:52:34 +08:00
}
2025-10-26 15:41:30 +08:00
l.format[key] = value
}
func (e *langError) SetCtx(ctxHttp context.Context) {
e.ctx = ctxHttp
}
2024-11-10 22:28:02 +08:00
func (l *langError) Error() string {
2025-10-26 15:52:32 +08:00
errLang := GetCtxLang(l.ctx)
return GetFormat(errLang, 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)
2025-08-22 14:23:30 +08:00
}
2024-11-10 22:28:02 +08:00
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,
}
}
2025-10-26 15:52:32 +08:00
func NewStruct(ctx context.Context, key string, format map[string]string) LangError {
2025-10-26 15:41:30 +08:00
return &langError{
ctx: ctx,
key: key,
format: format,
}
2024-06-30 11:52:34 +08:00
}