error.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package util
  2. import (
  3. "errors"
  4. "github.com/sirupsen/logrus"
  5. )
  6. type ContextualError struct {
  7. RealError error
  8. Fields map[string]interface{}
  9. Context string
  10. }
  11. func NewContextualError(msg string, fields map[string]interface{}, realError error) *ContextualError {
  12. return &ContextualError{Context: msg, Fields: fields, RealError: realError}
  13. }
  14. // ContextualizeIfNeeded is a helper function to turn an error into a ContextualError if it is not already one
  15. func ContextualizeIfNeeded(msg string, err error) error {
  16. switch err.(type) {
  17. case *ContextualError:
  18. return err
  19. default:
  20. return NewContextualError(msg, nil, err)
  21. }
  22. }
  23. // LogWithContextIfNeeded is a helper function to log an error line for an error or ContextualError
  24. func LogWithContextIfNeeded(msg string, err error, l *logrus.Logger) {
  25. switch v := err.(type) {
  26. case *ContextualError:
  27. v.Log(l)
  28. default:
  29. l.WithError(err).Error(msg)
  30. }
  31. }
  32. func (ce *ContextualError) Error() string {
  33. if ce.RealError == nil {
  34. return ce.Context
  35. }
  36. return ce.RealError.Error()
  37. }
  38. func (ce *ContextualError) Unwrap() error {
  39. if ce.RealError == nil {
  40. return errors.New(ce.Context)
  41. }
  42. return ce.RealError
  43. }
  44. func (ce *ContextualError) Log(lr *logrus.Logger) {
  45. if ce.RealError != nil {
  46. lr.WithFields(ce.Fields).WithError(ce.RealError).Error(ce.Context)
  47. } else {
  48. lr.WithFields(ce.Fields).Error(ce.Context)
  49. }
  50. }