Files
open-im-server/pkg/errs/coderr.go
T

110 lines
1.8 KiB
Go
Raw Normal View History

2023-02-15 17:00:55 +08:00
package errs
import (
"fmt"
"github.com/pkg/errors"
"strings"
)
2023-03-07 16:57:49 +08:00
type CodeError interface {
2023-02-15 17:00:55 +08:00
Code() int
Msg() string
2023-03-16 16:32:42 +08:00
Detail() string
WithDetail(detail string) CodeError
2023-03-20 14:36:42 +08:00
// Is 判断是否是某个错误, loose为false时, 只有错误码相同就认为是同一个错误, 默认为true
Is(err error, loose ...bool) bool
2023-03-07 12:19:30 +08:00
Wrap(msg ...string) error
2023-02-15 17:00:55 +08:00
error
}
2023-03-07 16:57:49 +08:00
func NewCodeError(code int, msg string) CodeError {
return &codeError{
2023-02-15 17:00:55 +08:00
code: code,
msg: msg,
}
}
2023-03-07 16:57:49 +08:00
type codeError struct {
2023-02-15 17:00:55 +08:00
code int
msg string
detail string
}
2023-03-07 16:57:49 +08:00
func (e *codeError) Code() int {
2023-02-15 17:00:55 +08:00
return e.code
}
2023-03-07 16:57:49 +08:00
func (e *codeError) Msg() string {
2023-02-15 17:00:55 +08:00
return e.msg
}
2023-03-16 16:32:42 +08:00
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,
}
}
2023-03-07 16:57:49 +08:00
func (e *codeError) Wrap(w ...string) error {
2023-02-15 17:00:55 +08:00
return errors.Wrap(e, strings.Join(w, ", "))
}
2023-03-20 14:36:42 +08:00
func (e *codeError) Is(err error, loose ...bool) bool {
2023-03-14 19:33:44 +08:00
if err == nil {
return false
}
2023-03-20 14:36:42 +08:00
var allowSubclasses bool
if len(loose) == 0 {
allowSubclasses = true
} else {
allowSubclasses = loose[0]
}
2023-03-14 19:33:44 +08:00
codeErr, ok := Unwrap(err).(CodeError)
if ok {
2023-03-20 14:36:42 +08:00
if allowSubclasses {
return Relation.Is(e.code, codeErr.Code())
} else {
return codeErr.Code() == e.code
}
2023-03-14 19:33:44 +08:00
}
return false
}
2023-03-07 16:57:49 +08:00
func (e *codeError) Error() string {
2023-06-02 14:40:22 +08:00
return fmt.Sprintf("%s", e.msg)
2023-02-15 17:00:55 +08:00
}
func Unwrap(err error) error {
2023-03-07 12:19:30 +08:00
for err != nil {
unwrap, ok := err.(interface {
Unwrap() error
})
if !ok {
break
}
err = unwrap.Unwrap()
}
return err
2023-02-15 17:00:55 +08:00
}
2023-03-17 16:08:13 +08:00
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, ", "))
}