You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5 KiB

  1. // Copyright 2013, 2014 Canonical Ltd.
  2. // Licensed under the LGPLv3, see LICENCE file for details.
  3. /*
  4. [godoc-link-here]
  5. The juju/errors provides an easy way to annotate errors without losing the
  6. orginal error context.
  7. The exported `New` and `Errorf` functions are designed to replace the
  8. `errors.New` and `fmt.Errorf` functions respectively. The same underlying
  9. error is there, but the package also records the location at which the error
  10. was created.
  11. A primary use case for this library is to add extra context any time an
  12. error is returned from a function.
  13. if err := SomeFunc(); err != nil {
  14. return err
  15. }
  16. This instead becomes:
  17. if err := SomeFunc(); err != nil {
  18. return errors.Trace(err)
  19. }
  20. which just records the file and line number of the Trace call, or
  21. if err := SomeFunc(); err != nil {
  22. return errors.Annotate(err, "more context")
  23. }
  24. which also adds an annotation to the error.
  25. When you want to check to see if an error is of a particular type, a helper
  26. function is normally exported by the package that returned the error, like the
  27. `os` package does. The underlying cause of the error is available using the
  28. `Cause` function.
  29. os.IsNotExist(errors.Cause(err))
  30. The result of the `Error()` call on an annotated error is the annotations joined
  31. with colons, then the result of the `Error()` method for the underlying error
  32. that was the cause.
  33. err := errors.Errorf("original")
  34. err = errors.Annotatef(err, "context")
  35. err = errors.Annotatef(err, "more context")
  36. err.Error() -> "more context: context: original"
  37. Obviously recording the file, line and functions is not very useful if you
  38. cannot get them back out again.
  39. errors.ErrorStack(err)
  40. will return something like:
  41. first error
  42. github.com/juju/errors/annotation_test.go:193:
  43. github.com/juju/errors/annotation_test.go:194: annotation
  44. github.com/juju/errors/annotation_test.go:195:
  45. github.com/juju/errors/annotation_test.go:196: more context
  46. github.com/juju/errors/annotation_test.go:197:
  47. The first error was generated by an external system, so there was no location
  48. associated. The second, fourth, and last lines were generated with Trace calls,
  49. and the other two through Annotate.
  50. Sometimes when responding to an error you want to return a more specific error
  51. for the situation.
  52. if err := FindField(field); err != nil {
  53. return errors.Wrap(err, errors.NotFoundf(field))
  54. }
  55. This returns an error where the complete error stack is still available, and
  56. `errors.Cause()` will return the `NotFound` error.
  57. */
  58. package errors