github.com/mailgun/holster/v4@v4.20.0/errors/with_context.go (about) 1 package errors 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/mailgun/holster/v4/callstack" 8 ) 9 10 // Implement this interface to pass along unstructured context to the logger 11 type HasContext interface { 12 Context() map[string]interface{} 13 } 14 15 // True if the interface has the format method (from fmt package) 16 type HasFormat interface { 17 Format(st fmt.State, verb rune) 18 } 19 20 // Creates errors that conform to the `HasContext` interface 21 type WithContext map[string]interface{} 22 23 // Wrapf returns an error annotating err with a stack trace 24 // at the point Wrapf is call, and the format specifier. 25 // If err is nil, Wrapf returns nil. 26 func (c WithContext) Wrapf(err error, format string, args ...interface{}) error { 27 if err == nil { 28 return nil 29 } 30 return &withContext{ 31 stack: callstack.New(1), 32 context: c, 33 cause: err, 34 msg: fmt.Sprintf(format, args...), 35 } 36 } 37 38 // Wrap returns an error annotating err with a stack trace 39 // at the point Wrap is called, and the supplied message. 40 // If err is nil, Wrap returns nil. 41 func (c WithContext) Wrap(err error, msg string) error { 42 if err == nil { 43 return nil 44 } 45 return &withContext{ 46 stack: callstack.New(1), 47 context: c, 48 cause: err, 49 msg: msg, 50 } 51 } 52 53 func (c WithContext) Error(msg string) error { 54 return &withContext{ 55 stack: callstack.New(1), 56 context: c, 57 cause: errors.New(msg), 58 msg: "", 59 } 60 } 61 62 func (c WithContext) Errorf(format string, args ...interface{}) error { 63 return &withContext{ 64 stack: callstack.New(1), 65 context: c, 66 cause: fmt.Errorf(format, args...), 67 msg: "", 68 } 69 }