error.go 809 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. func (ce ContextualError) Error() string {
  15. if ce.RealError == nil {
  16. return ce.Context
  17. }
  18. return ce.RealError.Error()
  19. }
  20. func (ce ContextualError) Unwrap() error {
  21. if ce.RealError == nil {
  22. return errors.New(ce.Context)
  23. }
  24. return ce.RealError
  25. }
  26. func (ce *ContextualError) Log(lr *logrus.Logger) {
  27. if ce.RealError != nil {
  28. lr.WithFields(ce.Fields).WithError(ce.RealError).Error(ce.Context)
  29. } else {
  30. lr.WithFields(ce.Fields).Error(ce.Context)
  31. }
  32. }