Files
errorx/errorx.go
T

98 lines
2.1 KiB
Go
Raw Normal View History

2023-12-27 19:08:09 +08:00
package errorx
import (
2025-10-26 20:32:02 +08:00
"context"
2023-12-27 19:08:09 +08:00
2025-10-26 20:32:02 +08:00
"github.com/yuninks/langx"
2023-12-27 19:08:09 +08:00
)
2025-10-26 20:32:02 +08:00
// Key生成错误信息
2023-12-27 19:08:09 +08:00
2025-10-26 20:32:02 +08:00
type LangError interface {
Copy() LangError // 复制一个新的错误信息
Error() string // 实现error接口&获取翻译后的错误信息
GetCode() int // 获取翻译后的Code
GetKey() string // 获取原Key值
GetFormat() map[string]string // 获取附加数据
SetFormat(format map[string]string) // 设置附加数据
SetCtx(ctxHttp context.Context) // 设置上下文
SetLang(lang string) // 设置语言
SetFormatKV(key, value string) // 设置附加数据键值对
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
type langError struct {
ctx context.Context
key string
format map[string]string
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (l *langError) Copy() LangError {
return &langError{
ctx: l.ctx,
key: l.key,
format: l.format,
2023-12-27 19:08:09 +08:00
}
}
2025-10-26 20:32:02 +08:00
func (e *langError) SetFormat(format map[string]string) {
e.format = format
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (l *langError) SetFormatKV(key, value string) {
if l.format == nil {
l.format = make(map[string]string)
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
l.format[key] = value
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (e *langError) SetCtx(ctxHttp context.Context) {
e.ctx = ctxHttp
}
2023-12-27 19:08:09 +08:00
2025-10-26 20:32:02 +08:00
func (l *langError) Error() string {
errLang := langx.GetCtxLang(l.ctx)
return langx.GetFormat(errLang, l.key, l.format)
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (e *langError) GetCode() int {
return langx.GetCode(e.key)
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (e *langError) GetKey() string {
return e.key
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (e *langError) GetFormat() map[string]string {
if e.format == nil {
e.format = make(map[string]string)
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
return e.format
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func (e *langError) SetLang(lang string) {
e.ctx = langx.SetCtxLang(e.ctx, lang)
}
func NewErrorf(ctx context.Context, key string, format map[string]string) error {
return &langError{
ctx: ctx,
key: key,
format: format,
}
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func NewError(ctx context.Context, key string) error {
return &langError{
ctx: ctx,
key: key,
}
2023-12-27 19:08:09 +08:00
}
2025-10-26 20:32:02 +08:00
func NewStruct(ctx context.Context, key string, format map[string]string) LangError {
return &langError{
ctx: ctx,
key: key,
format: format,
}
2023-12-27 19:08:09 +08:00
}