example_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package errors_test
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/pkg/errors"
  6. )
  7. func ExampleNew() {
  8. err := errors.New("whoops")
  9. fmt.Println(err)
  10. // Output: whoops
  11. }
  12. func ExampleNew_printf() {
  13. err := errors.New("whoops")
  14. fmt.Printf("%+v", err)
  15. // Output: github.com/pkg/errors/example_test.go:18: whoops
  16. }
  17. func ExampleWrap() {
  18. cause := errors.New("whoops")
  19. err := errors.Wrap(cause, "oh noes")
  20. fmt.Println(err)
  21. // Output: oh noes: whoops
  22. }
  23. func fn() error {
  24. e1 := errors.New("error")
  25. e2 := errors.Wrap(e1, "inner")
  26. e3 := errors.Wrap(e2, "middle")
  27. return errors.Wrap(e3, "outer")
  28. }
  29. func ExampleCause() {
  30. err := fn()
  31. fmt.Println(err)
  32. fmt.Println(errors.Cause(err))
  33. // Output: outer: middle: inner: error
  34. // error
  35. }
  36. func ExampleFprint() {
  37. err := fn()
  38. errors.Fprint(os.Stdout, err)
  39. // Output: github.com/pkg/errors/example_test.go:33: error
  40. // github.com/pkg/errors/example_test.go:34: inner
  41. // github.com/pkg/errors/example_test.go:35: middle
  42. // github.com/pkg/errors/example_test.go:36: outer
  43. }
  44. func ExampleWrapf() {
  45. cause := errors.New("whoops")
  46. err := errors.Wrapf(cause, "oh noes #%d", 2)
  47. fmt.Println(err)
  48. // Output: oh noes #2: whoops
  49. }
  50. func ExampleErrorf() {
  51. err := errors.Errorf("whoops: %s", "foo")
  52. fmt.Printf("%+v", err)
  53. // Output: github.com/pkg/errors/example_test.go:67: whoops: foo
  54. }
  55. func Example_stacktrace() {
  56. type Stacktrace interface {
  57. Stacktrace() []errors.Frame
  58. }
  59. err, ok := errors.Cause(fn()).(Stacktrace)
  60. if !ok {
  61. panic("oops, err does not implement Stacktrace")
  62. }
  63. st := err.Stacktrace()
  64. fmt.Printf("%+v", st[0:2]) // top two frames
  65. // Output: [github.com/pkg/errors/example_test.go:33 github.com/pkg/errors/example_test.go:78]
  66. }