You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Open-IM-Server/pkg/errs/coderr.go

110 lines
1.8 KiB

2 years ago
package errs
import (
"fmt"
"github.com/pkg/errors"
"strings"
)
2 years ago
type CodeError interface {
2 years ago
Code() int
Msg() string
2 years ago
Detail() string
WithDetail(detail string) CodeError
2 years ago
// Is 判断是否是某个错误, loose为false时, 只有错误码相同就认为是同一个错误, 默认为true
Is(err error, loose ...bool) bool
2 years ago
Wrap(msg ...string) error
2 years ago
error
}
2 years ago
func NewCodeError(code int, msg string) CodeError {
return &codeError{
2 years ago
code: code,
msg: msg,
}
}
2 years ago
type codeError struct {
2 years ago
code int
msg string
detail string
}
2 years ago
func (e *codeError) Code() int {
2 years ago
return e.code
}
2 years ago
func (e *codeError) Msg() string {
2 years ago
return e.msg
}
2 years ago
func (e *codeError) Detail() string {
return e.detail
}
func (e *codeError) WithDetail(detail string) CodeError {
var d string
if e.detail == "" {
d = detail
} else {
d = e.detail + ", " + detail
}
return &codeError{
code: e.code,
msg: e.msg,
detail: d,
}
}
2 years ago
func (e *codeError) Wrap(w ...string) error {
2 years ago
return errors.Wrap(e, strings.Join(w, ", "))
}
2 years ago
func (e *codeError) Is(err error, loose ...bool) bool {
2 years ago
if err == nil {
return false
}
2 years ago
var allowSubclasses bool
if len(loose) == 0 {
allowSubclasses = true
} else {
allowSubclasses = loose[0]
}
2 years ago
codeErr, ok := Unwrap(err).(CodeError)
if ok {
2 years ago
if allowSubclasses {
return Relation.Is(e.code, codeErr.Code())
} else {
return codeErr.Code() == e.code
}
2 years ago
}
return false
}
2 years ago
func (e *codeError) Error() string {
2 years ago
return fmt.Sprintf("[%d]%s", e.code, e.msg)
}
func Unwrap(err error) error {
2 years ago
for err != nil {
unwrap, ok := err.(interface {
Unwrap() error
})
if !ok {
break
}
err = unwrap.Unwrap()
}
return err
2 years ago
}
2 years ago
func Wrap(err error, msg ...string) error {
if err == nil {
return nil
}
if len(msg) == 0 {
return errors.WithStack(err)
}
return errors.Wrap(err, strings.Join(msg, ", "))
}