优化Error的封装

This commit is contained in:
Yun
2024-07-24 19:47:00 +08:00
parent d9fdeabf85
commit ea8d17943d
3 changed files with 23 additions and 10 deletions
+16 -7
View File
@@ -4,7 +4,16 @@ import (
"context" "context"
) )
type LangError struct { type LangError interface {
NewError(ctx context.Context, key string) error
NewErrorFormat(ctx context.Context, key string, format map[string]string) error
Error() string
GetCode() int
GetMsg() string
GetFormat() map[string]string
}
type langError struct {
ctx context.Context ctx context.Context
key string key string
format map[string]string format map[string]string
@@ -14,7 +23,7 @@ type errorConst string
const errorLang errorConst = "errorLang" const errorLang errorConst = "errorLang"
func (e *LangError) Error() string { func (e *langError) Error() string {
errLang := e.ctx.Value(errorLang) errLang := e.ctx.Value(errorLang)
l := "" l := ""
if errLang != nil { if errLang != nil {
@@ -23,15 +32,15 @@ func (e *LangError) Error() string {
return GetFormat(l, e.key, e.format) return GetFormat(l, e.key, e.format)
} }
func (e *LangError) GetCode() int { func (e *langError) GetCode() int {
return GetCode(e.key) return GetCode(e.key)
} }
func (e *LangError) GetMsg() string { func (e *langError) GetMsg() string {
return e.key return e.key
} }
func (e *LangError) GetFormat() map[string]string { func (e *langError) GetFormat() map[string]string {
if e.format == nil { if e.format == nil {
e.format = make(map[string]string) e.format = make(map[string]string)
} }
@@ -39,7 +48,7 @@ func (e *LangError) GetFormat() map[string]string {
} }
func NewErrorFormat(ctx context.Context, key string, format map[string]string) error { func NewErrorFormat(ctx context.Context, key string, format map[string]string) error {
return &LangError{ return &langError{
ctx: ctx, ctx: ctx,
key: key, key: key,
format: format, format: format,
@@ -47,7 +56,7 @@ func NewErrorFormat(ctx context.Context, key string, format map[string]string) e
} }
func NewError(ctx context.Context, key string) error { func NewError(ctx context.Context, key string) error {
return &LangError{ return &langError{
ctx: ctx, ctx: ctx,
key: key, key: key,
} }
+2 -2
View File
@@ -35,7 +35,7 @@ func TestError(t *testing.T) {
err = langx.NewError(ctx, "error") err = langx.NewError(ctx, "error")
// fmt.Printf("err: %v\n", err) // fmt.Printf("err: %v\n", err)
t.Log(err.Error()) t.Log(err.Error())
val, ok := err.(*langx.LangError) val, ok := err.(langx.LangError)
if ok { if ok {
t.Log(val.GetCode()) t.Log(val.GetCode())
} }
@@ -44,7 +44,7 @@ func TestError(t *testing.T) {
"name": "yuninks", "name": "yuninks",
}) })
t.Log(err.Error()) t.Log(err.Error())
val, ok = err.(*langx.LangError) val, ok = err.(langx.LangError)
if ok { if ok {
t.Log(val.GetCode()) t.Log(val.GetCode())
} }
+5 -1
View File
@@ -1,5 +1,9 @@
# 简介 # 简介
这是简单的一个多语言响应工具 这是简单的一个多语言响应工具,能够通过多种方式加载资源文件,然后进行匹配。同时支持占位符替换的形式在多语言响应的时候替换特定字符,让响应更友好。
# 使用方法
看example