From 67ace9fbe060dfaa73d80228a28d252f46472500 Mon Sep 17 00:00:00 2001 From: debidong <1953531014@qq.com> Date: Tue, 29 Oct 2024 15:13:41 +0800 Subject: [PATCH] feat: add i18n support for errorx.Bomb and errorx.Dangerous --- errorx/errorx.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/errorx/errorx.go b/errorx/errorx.go index 21c0a12..6055861 100644 --- a/errorx/errorx.go +++ b/errorx/errorx.go @@ -2,6 +2,9 @@ package errorx import ( "fmt" + + "github.com/gin-gonic/gin" + "github.com/toolkits/pkg/i18n" ) type PageError struct { @@ -21,6 +24,11 @@ func Bomb(code int, format string, a ...interface{}) { panic(PageError{Code: code, Message: fmt.Sprintf(format, a...)}) } +func BombWithI18n(ctx *gin.Context, code int, format string, a ...interface{}) { + lang := ctx.GetHeader("X-Language") + panic(PageError{Code: code, Message: i18n.Sprintf(lang, format, a...)}) +} + func Dangerous(v interface{}, code ...int) { if v == nil { return @@ -40,3 +48,24 @@ func Dangerous(v interface{}, code ...int) { panic(PageError{Code: c, Message: t.Error()}) } } + +func DangerousWithI18n(ctx *gin.Context, v interface{}, code ...int) { + if v == nil { + return + } + + c := 200 + if len(code) > 0 { + c = code[0] + } + + lang := ctx.GetHeader("X-Language") + switch t := v.(type) { + case string: + if t != "" { + panic(PageError{Code: c, Message: i18n.Sprintf(lang, t)}) + } + case error: + panic(PageError{Code: c, Message: i18n.Sprintf(lang, t.Error())}) + } +}