error.go 934 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package util
  2. import "errors"
  3. type ErrorWithExtraData interface {
  4. error
  5. Serialize(desc string) ([] byte)
  6. LookupExtraData(key string) (string, bool)
  7. }
  8. type WrappedErrorWithExtraData struct {
  9. Underlying ErrorWithExtraData
  10. Description string
  11. }
  12. func (e *WrappedErrorWithExtraData) Error() string {
  13. return e.Underlying.Error()
  14. }
  15. func (e *WrappedErrorWithExtraData) Serialize(desc string) ([] byte) {
  16. if desc == "" {
  17. desc = e.Description
  18. }
  19. return e.Underlying.Serialize(desc)
  20. }
  21. func (e *WrappedErrorWithExtraData) LookupExtraData(key string) (string, bool) {
  22. return e.Underlying.LookupExtraData(key)
  23. }
  24. func WrapError(e error, wrap func(string)(string)) error {
  25. var wrapped_desc = wrap(e.Error())
  26. var e_with_extra, with_extra = e.(ErrorWithExtraData)
  27. if with_extra {
  28. return &WrappedErrorWithExtraData {
  29. Underlying: e_with_extra,
  30. Description: wrapped_desc,
  31. }
  32. } else {
  33. return errors.New(wrapped_desc)
  34. }
  35. }