github.com/influxdata/influxdb/v2@v2.7.6/kit/errors/errors.go (about) 1 package errors2 2 3 import ( 4 "fmt" 5 "net/http" 6 ) 7 8 // TODO: move to base directory 9 10 const ( 11 // InternalError indicates an unexpected error condition. 12 InternalError = 1 13 // MalformedData indicates malformed input, such as unparsable JSON. 14 MalformedData = 2 15 // InvalidData indicates that data is well-formed, but invalid. 16 InvalidData = 3 17 // Forbidden indicates a forbidden operation. 18 Forbidden = 4 19 // NotFound indicates a resource was not found. 20 NotFound = 5 21 ) 22 23 // Error indicates an error with a reference code and an HTTP status code. 24 type Error struct { 25 Reference int `json:"referenceCode"` 26 Code int `json:"statusCode"` 27 Err string `json:"err"` 28 } 29 30 // Error implements the error interface. 31 func (e Error) Error() string { 32 return e.Err 33 } 34 35 // Errorf constructs an Error with the given reference code and format. 36 func Errorf(ref int, format string, i ...interface{}) error { 37 return Error{ 38 Reference: ref, 39 Err: fmt.Sprintf(format, i...), 40 } 41 } 42 43 // New creates a new error with a message and error code. 44 func New(msg string, ref ...int) error { 45 refCode := InternalError 46 if len(ref) == 1 { 47 refCode = ref[0] 48 } 49 return Error{ 50 Reference: refCode, 51 Err: msg, 52 } 53 } 54 55 func Wrap(err error, msg string, ref ...int) error { 56 if err == nil { 57 return nil 58 } 59 e, ok := err.(Error) 60 if ok { 61 refCode := e.Reference 62 if len(ref) == 1 { 63 refCode = ref[0] 64 } 65 return Error{ 66 Reference: refCode, 67 Code: e.Code, 68 Err: fmt.Sprintf("%s: %s", msg, e.Err), 69 } 70 } 71 refCode := InternalError 72 if len(ref) == 1 { 73 refCode = ref[0] 74 } 75 return Error{ 76 Reference: refCode, 77 Err: fmt.Sprintf("%s: %s", msg, err.Error()), 78 } 79 } 80 81 // InternalErrorf constructs an InternalError with the given format. 82 func InternalErrorf(format string, i ...interface{}) error { 83 return Errorf(InternalError, format, i...) 84 } 85 86 // MalformedDataf constructs a MalformedData error with the given format. 87 func MalformedDataf(format string, i ...interface{}) error { 88 return Errorf(MalformedData, format, i...) 89 } 90 91 // InvalidDataf constructs an InvalidData error with the given format. 92 func InvalidDataf(format string, i ...interface{}) error { 93 return Errorf(InvalidData, format, i...) 94 } 95 96 // Forbiddenf constructs a Forbidden error with the given format. 97 func Forbiddenf(format string, i ...interface{}) error { 98 return Errorf(Forbidden, format, i...) 99 } 100 101 func BadRequestError(msg string) error { 102 return Error{ 103 Reference: InvalidData, 104 Code: http.StatusBadRequest, 105 Err: msg, 106 } 107 }