github.com/sandwich-go/boost@v1.3.29/xerror/xerror_new.go (about) 1 package xerror 2 3 import "fmt" 4 5 // Errorf returns an error that formats as the given format and args. 6 var Errorf = NewText 7 8 // NewText returns an error that formats as the given format and args. 9 func NewText(format string, args ...interface{}) *Error { 10 text := format 11 if len(args) != 0 { 12 text = fmt.Sprintf(format, args...) 13 } 14 return &Error{ 15 callStack: callersCheckIsErrorWithStack(1), 16 text: text, 17 code: ErrorCodeUnsetAsDefault, 18 } 19 } 20 21 // proto-gen-go v2 22 // https://github.com/golang/protobuf/blob/5b6d0471e5bd463898a8121123ace60c7a0d9ca7/reflect/protoreflect/value.go#L9-L22 23 type protoEnum interface { 24 fmt.Stringer 25 NumberInt32() int32 26 EnumDescriptor() ([]byte, []int) 27 } 28 29 // NewCode 根据错误码和指定的format, args(可为空)构造错误信息 30 func NewCode(code int32, format string, args ...interface{}) *Error { 31 text := format 32 if len(args) != 0 { 33 text = fmt.Sprintf(format, args...) 34 } 35 return &Error{ 36 callStack: callersCheckIsErrorWithStack(1), 37 text: text, 38 code: code, 39 } 40 } 41 42 // NewProtoEnum 根据proto enum错误码和指定的format, args(可为空)构造错误信息 43 func NewProtoEnum(code protoEnum) *Error { 44 return &Error{ 45 callStack: callersCheckIsErrorWithStack(1), 46 text: code.String(), 47 code: code.NumberInt32(), 48 } 49 } 50 51 // Wrap 封装底层错误,提供另一个错误信息,如果error为nil则返回nil 52 func Wrap(err error, format string, args ...interface{}) error { 53 if err == nil { 54 return nil 55 } 56 text := format 57 if len(args) != 0 { 58 text = fmt.Sprintf(format, args...) 59 } 60 return &Error{ 61 err: err, 62 callStack: callersCheckIsErrorWithStack(1), 63 text: text, 64 code: Code(err), 65 logic: Logic(err), 66 } 67 } 68 69 // WrapCode 封装底层错误,指定错误码,如果error为nil则返回nil 70 func WrapCode(code int32, err error, format string, args ...interface{}) error { 71 if err == nil { 72 return nil 73 } 74 text := format 75 if len(args) != 0 { 76 text = fmt.Sprintf(format, args...) 77 } 78 return &Error{ 79 err: err, 80 callStack: callersCheckIsErrorWithStack(1), 81 text: text, 82 code: code, 83 logic: Logic(err), 84 } 85 } 86 87 // WrapProtoEnum 封装底层错误,指定proto Enum错误码,如果error为nil则返回nil 88 func WrapProtoEnum(code protoEnum, err error) error { 89 if err == nil { 90 return nil 91 } 92 return &Error{ 93 err: err, 94 callStack: callersCheckIsErrorWithStack(1), 95 text: code.String(), 96 code: code.NumberInt32(), 97 logic: Logic(err), 98 } 99 }