github.com/0chain/gosdk@v1.17.11/zcnbridge/errors/errors.go (about) 1 // Error struct and functions. 2 package errors 3 4 import ( 5 "errors" 6 "fmt" 7 "os" 8 ) 9 10 const ( 11 delim = ": " 12 ) 13 14 type ( 15 // Error type for a new application error. 16 Error struct { 17 Code string `json:"code,omitempty"` 18 Msg string `json:"msg"` 19 } 20 ) 21 22 type ( 23 // ErrWrapper implements error wrapper interface. 24 ErrWrapper struct { 25 code string 26 text string 27 wrap error 28 } 29 ) 30 31 // Error implements error interface. 32 func (e *ErrWrapper) Error() string { 33 return e.code + delim + e.text 34 } 35 36 // Unwrap implements error unwrap interface. 37 func (e *ErrWrapper) Unwrap() error { 38 return e.wrap 39 } 40 41 // Wrap implements error wrapper interface. 42 func (e *ErrWrapper) Wrap(err error) *ErrWrapper { 43 return Wrap(e.code, e.text, err) 44 } 45 46 // Any reports whether an error in error's chain 47 // matches to any error provided in list. 48 func Any(err error, targets ...error) bool { 49 for _, target := range targets { 50 if errors.Is(err, target) { 51 return true 52 } 53 } 54 55 return false 56 } 57 58 // ExitErr prints error to os.Stderr and call os.Exit with given code. 59 func ExitErr(text string, err error, code int) { 60 text = Wrap("exit", text, err).Error() 61 _, _ = os.Stderr.Write([]byte(text)) 62 os.Exit(code) 63 } 64 65 // ExitMsg prints message to os.Stderr and call os.Exit with given code. 66 func ExitMsg(text string, code int) { 67 text = New("exit", text).Error() 68 _, _ = os.Stderr.Write([]byte(text)) 69 os.Exit(code) 70 } 71 72 // Is checks if error is equal to target error. 73 // - err: error to check 74 // - target: target error to compare 75 func Is(err, target error) bool { 76 return errors.Is(err, target) 77 } 78 79 // New returns constructed error wrapper interface. 80 func New(code, text string) *ErrWrapper { 81 return &ErrWrapper{code: code, text: text} 82 } 83 84 // Wrap wraps given error into a new error with format. 85 func Wrap(code, text string, err error) *ErrWrapper { 86 wrapper := &ErrWrapper{code: code, text: text} 87 if err != nil && !errors.Is(wrapper, err) { 88 wrapper.wrap = err 89 wrapper.text += delim + err.Error() 90 } 91 92 return wrapper 93 } 94 95 func (err *Error) Error() string { 96 return fmt.Sprintf("%s: %s", err.Code, err.Msg) 97 } 98 99 // NewError create a new error instance given a code and a message. 100 // - code: error code 101 // - msg: error message 102 func NewError(code string, msg string) *Error { 103 return &Error{Code: code, Msg: msg} 104 } 105 106 /*NewErrorf - create a new error with format */ 107 func NewErrorf(code string, format string, args ...interface{}) *Error { 108 return &Error{Code: code, Msg: fmt.Sprintf(format, args...)} 109 }