github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/stub/error.go (about) 1 package stub 2 3 import ( 4 "fmt" 5 6 "github.com/clubpay/ronykit/kit" 7 ) 8 9 type Error struct { 10 code int 11 item string 12 msg kit.Message 13 err error 14 } 15 16 func NewError(code int, item string) *Error { 17 return &Error{ 18 code: code, 19 item: item, 20 } 21 } 22 23 func NewErrorWithMsg(msg kit.Message) *Error { 24 wErr := &Error{ 25 msg: msg, 26 } 27 if e, ok := msg.(interface{ GetCode() int }); ok { 28 wErr.code = e.GetCode() 29 } 30 if e, ok := msg.(interface{ GetItem() string }); ok { 31 wErr.item = e.GetItem() 32 } 33 34 return wErr 35 } 36 37 func WrapError(err error) *Error { 38 if err == nil { 39 return nil 40 } 41 42 return &Error{err: err} 43 } 44 45 func (err Error) Error() string { 46 if err.err != nil { 47 return err.err.Error() 48 } 49 50 return fmt.Sprintf("ERR(%d): %s", err.code, err.item) 51 } 52 53 func (err Error) Msg() kit.Message { 54 return err.msg 55 } 56 57 func (err Error) Code() int { 58 return err.code 59 } 60 61 func (err Error) Item() string { 62 return err.item 63 } 64 65 func (err Error) Is(target error) bool { 66 var cond bool 67 //nolint:errorlint 68 switch e := target.(type) { 69 case Error: 70 cond = e.err == nil && e.code == err.code && e.item == err.item 71 72 case *Error: 73 cond = e.err == nil && e.code == err.code && e.item == err.item 74 } 75 76 return cond 77 } 78 79 func (err Error) Unwrap() error { 80 return err.err 81 }