github.com/hyperledger/burrow@v0.34.5-0.20220512172541-77f09336001d/execution/errors/exception.go (about) 1 package errors 2 3 import "fmt" 4 5 func NewException(code *Code, exception string) *Exception { 6 if exception == "" { 7 return nil 8 } 9 return &Exception{ 10 CodeNumber: code.Number, 11 Exception: exception, 12 } 13 } 14 15 // Wraps any error as a Exception 16 func AsException(err error) *Exception { 17 if err == nil { 18 return nil 19 } 20 switch e := err.(type) { 21 case *Exception: 22 return e 23 case CodedError: 24 return NewException(e.ErrorCode(), e.ErrorMessage()) 25 default: 26 return NewException(Codes.Generic, err.Error()) 27 } 28 } 29 30 func Wrapf(err error, format string, a ...interface{}) *Exception { 31 ex := AsException(err) 32 return NewException(Codes.Get(ex.CodeNumber), fmt.Sprintf(format, a...)) 33 } 34 35 func Wrap(err error, message string) *Exception { 36 ex := AsException(err) 37 return NewException(Codes.Get(ex.CodeNumber), message+": "+ex.Exception) 38 } 39 40 func Errorf(code *Code, format string, a ...interface{}) *Exception { 41 return NewException(code, fmt.Sprintf(format, a...)) 42 } 43 44 func (e *Exception) AsError() error { 45 // We need to return a bare untyped error here so that err == nil downstream 46 if e == nil { 47 return nil 48 } 49 return e 50 } 51 52 func (e *Exception) ErrorCode() *Code { 53 return Codes.Get(e.CodeNumber) 54 } 55 56 func (e *Exception) Error() string { 57 return fmt.Sprintf("error %d - %s: %s", e.CodeNumber, Codes.Get(e.CodeNumber), e.Exception) 58 } 59 60 func (e *Exception) String() string { 61 return e.Error() 62 } 63 64 func (e *Exception) ErrorMessage() string { 65 if e == nil { 66 return "" 67 } 68 return e.Exception 69 } 70 71 func (e *Exception) Equal(ce CodedError) bool { 72 ex := AsException(ce) 73 if e == nil || ex == nil { 74 return e == nil && ex == nil 75 } 76 return e.CodeNumber == ex.CodeNumber && e.Exception == ex.Exception 77 } 78 79 func (e *Exception) GetCode() *Code { 80 return Codes.Get(e.CodeNumber) 81 }