Files
open-im-server/pkg/common/constant/error_info.go
T

67 lines
1.3 KiB
Go
Raw Normal View History

2023-01-12 16:48:11 +08:00
package constant
import (
"encoding/json"
2023-01-12 17:30:48 +08:00
"github.com/pkg/errors"
2023-01-12 16:48:11 +08:00
"gorm.io/gorm"
2023-01-12 17:52:14 +08:00
"strings"
2023-01-12 16:48:11 +08:00
)
type ErrInfo struct {
ErrCode int32
ErrMsg string
DetailErrMsg string
}
2023-01-13 18:29:25 +08:00
func NewErrInfo(code int32, msg, detail string) *ErrInfo {
return &ErrInfo{
ErrCode: code,
ErrMsg: msg,
DetailErrMsg: detail,
}
}
2023-01-12 16:48:11 +08:00
func (e *ErrInfo) Error() string {
2023-01-12 16:50:37 +08:00
return "errMsg: " + e.ErrMsg + " detail errMsg: " + e.DetailErrMsg
2023-01-12 16:48:11 +08:00
}
func (e *ErrInfo) Code() int32 {
return e.ErrCode
}
2023-01-12 17:52:14 +08:00
func (e *ErrInfo) Wrap(msg ...string) error {
return errors.Wrap(e, strings.Join(msg, "--"))
2023-01-12 17:17:42 +08:00
}
2023-01-12 16:48:11 +08:00
func NewErrNetwork(err error) error {
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrNetwork)
2023-01-12 16:48:11 +08:00
}
func NewErrData(err error) error {
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrData)
2023-01-12 16:48:11 +08:00
}
func toDetail(err error, info *ErrInfo) *ErrInfo {
errInfo := *info
errInfo.DetailErrMsg = err.Error()
return &errInfo
}
func ToAPIErrWithErr(err error) *ErrInfo {
errComm := errors.New("")
var marshalErr *json.MarshalerError
errInfo := &ErrInfo{}
switch {
case errors.As(err, &errComm):
if errors.Is(err, gorm.ErrRecordNotFound) {
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrRecordNotFound)
2023-01-12 16:48:11 +08:00
}
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrData)
2023-01-12 16:48:11 +08:00
case errors.As(err, &marshalErr):
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrData)
2023-01-12 16:48:11 +08:00
case errors.As(err, &errInfo):
return toDetail(err, errInfo)
}
2023-01-12 16:54:26 +08:00
return toDetail(err, ErrDefaultOther)
2023-01-12 16:48:11 +08:00
}