91 lines
1.7 KiB
Go
91 lines
1.7 KiB
Go
package ecode
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"server/utility/i18n"
|
|
|
|
"github.com/gogf/gf/v2/errors/gcode"
|
|
)
|
|
|
|
type Error struct {
|
|
code int
|
|
message string
|
|
sub string
|
|
params []interface{}
|
|
}
|
|
|
|
func New(code int, message string) Error {
|
|
return Error{
|
|
code: code,
|
|
message: message,
|
|
}
|
|
}
|
|
|
|
func (e Error) Params(params ...interface{}) Error {
|
|
e.params = append(e.params, params...)
|
|
return e
|
|
}
|
|
|
|
func (e Error) Error() string {
|
|
return e.Message()
|
|
}
|
|
|
|
func (e Error) Sub(sub string) Error {
|
|
e.sub = sub
|
|
return e
|
|
}
|
|
|
|
func (e Error) Message() string {
|
|
if e.message != "" && len(e.params) > 0 {
|
|
e.message = fmt.Sprintf(e.message, e.params...)
|
|
}
|
|
if e.sub != "" {
|
|
if e.message != "" {
|
|
if len(e.params) > 0 {
|
|
e.message = fmt.Sprintf(e.message, e.params...)
|
|
}
|
|
return fmt.Sprintf("%s:%s", e.message, e.sub)
|
|
}
|
|
return e.sub
|
|
}
|
|
return e.message
|
|
}
|
|
|
|
// MessageI18n 返回国际化消息
|
|
func (e Error) MessageI18n(ctx context.Context) string {
|
|
// 如果有子消息,优先使用子消息的国际化
|
|
if e.sub != "" {
|
|
return i18n.T(ctx, e.sub)
|
|
}
|
|
|
|
// 否则使用主消息的国际化
|
|
if e.message != "" {
|
|
// 尝试从国际化系统获取消息
|
|
i18nMsg := i18n.T(ctx, e.message)
|
|
if i18nMsg != e.message {
|
|
// 如果找到了国际化消息,使用它
|
|
if len(e.params) > 0 {
|
|
return fmt.Sprintf(i18nMsg, e.params...)
|
|
}
|
|
return i18nMsg
|
|
}
|
|
|
|
// 如果没有找到国际化消息,使用原来的逻辑
|
|
if len(e.params) > 0 {
|
|
return fmt.Sprintf(e.message, e.params...)
|
|
}
|
|
return e.message
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
func (e Error) Code() gcode.Code {
|
|
return gcode.New(e.code, e.Message(), "customer")
|
|
}
|
|
|
|
func (e Error) Detail() interface{} {
|
|
return "customer"
|
|
}
|