1 Star 0 Fork 0

GarlicBoris/gozero-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
error.go 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
yanwc 提交于 2024-11-21 09:36 +08:00 . refactor: error
package errx
import (
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Error struct {
code Code // 错误编码
msg string // 错误消息
inner error
}
func (e *Error) GetErrCode() Code {
return e.code
}
func (e *Error) InnerError() error {
return e.inner
}
// Equal 对比错误码是否相等
func Equal(err error, code Code) bool {
return status.Code(err) == codes.Code(code)
}
func (e *Error) Error() string {
return e.msg
}
// 错误消息
func (e *Error) GetMsg() string {
// 优先获取错误实例消息
if len(e.msg) != 0 {
return e.msg
}
// 获取默认全局定义的消息
if v, ok := message[e.code]; ok {
return v
} else {
return "未定义消息"
}
}
func New(code Code, opts ...ErrorOption) *Error {
err := Error{
code: code,
}
for _, opt := range opts {
opt(&err)
}
if err.code != SERVER && len(err.msg) == 0 {
if m, ok := message[err.code]; ok {
err.msg = m
}
}
if len(err.msg) == 0 {
err.msg = "未定义错误消息"
}
if err.inner != nil {
logx.ErrorStack(err.inner)
}
return &err
}
// NewBiz 业务错误,不打印日志
func NewBiz(msg string) *Error {
return New(BIZ, WithMsgOption(msg))
}
// NewNotFound 数据未找到
func NewNotFound(msg string) *Error {
return New(DB_NOT_FOUND, WithMsgOption(msg))
}
// NewDBQuery 数据库查询失败
func NewDBQuery(err error, msg string) *Error {
return New(DB_QUERY, WithErrorOption(err), WithMsgOption(msg))
}
// NewWithError 包含内部错误
func NewWithError(c Code, err error) *Error {
return New(c, WithErrorOption(err))
}
// NewWithMsg 包含自定义消息
func NewWithMsg(c Code, msg string) *Error {
return New(c, WithMsgOption(msg))
}
// NewWithErrorAndMsg 内部错误和自定义消息
func NewWithErrorAndMsg(c Code, err error, msg string) *Error {
return New(c, WithMsgOption(msg), WithErrorOption(err))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/yanwc/gozero-utils.git
git@gitee.com:yanwc/gozero-utils.git
yanwc
gozero-utils
gozero-utils
v1.3.78

搜索帮助