code error

This commit is contained in:
withchao 2023-03-20 14:36:42 +08:00
parent 99c486295b
commit e0a422fd16
4 changed files with 59 additions and 5 deletions

View File

@ -48,7 +48,7 @@ const (
// 群组错误码
GroupIDNotFoundError = 1201 //GroupID不存在
GroupIDIDExisted = 1202 //GroupID已存在
GroupIDExisted = 1202 //GroupID已存在
OnlyOneOwnerError = 1203 //只能有一个群主
InGroupAlreadyError = 1204 //已在群组中
NotInGroupYetError = 1205 //不在群组中

View File

@ -11,7 +11,8 @@ type CodeError interface {
Msg() string
Detail() string
WithDetail(detail string) CodeError
Is(err error) bool
// Is 判断是否是某个错误, loose为false时, 只有错误码相同就认为是同一个错误, 默认为true
Is(err error, loose ...bool) bool
Wrap(msg ...string) error
error
}
@ -59,13 +60,23 @@ func (e *codeError) Wrap(w ...string) error {
return errors.Wrap(e, strings.Join(w, ", "))
}
func (e *codeError) Is(err error) bool {
func (e *codeError) Is(err error, loose ...bool) bool {
if err == nil {
return false
}
var allowSubclasses bool
if len(loose) == 0 {
allowSubclasses = true
} else {
allowSubclasses = loose[0]
}
codeErr, ok := Unwrap(err).(CodeError)
if ok {
return codeErr.Code() == e.code
if allowSubclasses {
return Relation.Is(e.code, codeErr.Code())
} else {
return codeErr.Code() == e.code
}
}
return false
}

View File

@ -12,7 +12,7 @@ var (
ErrUserIDNotFound = NewCodeError(UserIDNotFoundError, "UserIDNotFoundError")
ErrGroupIDNotFound = NewCodeError(GroupIDNotFoundError, "GroupIDNotFoundError")
ErrGroupIDExisted = NewCodeError(GroupIDIDExisted, "GroupIDExisted")
ErrGroupIDExisted = NewCodeError(GroupIDExisted, "GroupIDExisted")
ErrUserIDExisted = NewCodeError(UserIDExisted, "UserIDExisted")
ErrRecordNotFound = NewCodeError(RecordNotFoundError, "RecordNotFoundError")

43
pkg/errs/relation.go Normal file
View File

@ -0,0 +1,43 @@
package errs
var Relation = &relation{m: make(map[int]map[int]struct{})}
func init() {
Relation.Add(RecordNotFoundError, UserIDNotFoundError)
Relation.Add(RecordNotFoundError, GroupIDNotFoundError)
Relation.Add(DuplicateKeyError, UserIDExisted)
Relation.Add(DuplicateKeyError, GroupIDExisted)
}
type relation struct {
m map[int]map[int]struct{}
}
func (r *relation) Add(codes ...int) {
if len(codes) < 2 {
panic("codes length must be greater than 2")
}
for i := 1; i < len(codes); i++ {
parent := codes[i-1]
s, ok := r.m[parent]
if !ok {
s = make(map[int]struct{})
r.m[parent] = s
}
for _, code := range codes[i:] {
s[code] = struct{}{}
}
}
}
func (r *relation) Is(parent, child int) bool {
if parent == child {
return true
}
s, ok := r.m[parent]
if !ok {
return false
}
_, ok = s[child]
return ok
}