errors.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Package errors provides simple error handling primitives.
  2. //
  3. // The traditional error handling idiom in Go is roughly akin to
  4. //
  5. // if err != nil {
  6. // return err
  7. // }
  8. //
  9. // which applied recursively up the call stack results in error reports
  10. // without context or debugging information. The errors package allows
  11. // programmers to add context to the failure path in their code in a way
  12. // that does not destroy the original value of the error.
  13. //
  14. // Adding context to an error
  15. //
  16. // The errors.Wrap function returns a new error that adds context to the
  17. // original error. For example
  18. //
  19. // _, err := ioutil.ReadAll(r)
  20. // if err != nil {
  21. // return errors.Wrap(err, "read failed")
  22. // }
  23. //
  24. // Retrieving the cause of an error
  25. //
  26. // Using errors.Wrap constructs a stack of errors, adding context to the
  27. // preceding error. Depending on the nature of the error it may be necessary
  28. // to reverse the operation of errors.Wrap to retrieve the original error
  29. // for inspection. Any error value which implements this interface
  30. //
  31. // type causer interface {
  32. // Cause() error
  33. // }
  34. //
  35. // can be inspected by errors.Cause. errors.Cause will recursively retrieve
  36. // the topmost error which does not implement causer, which is assumed to be
  37. // the original cause. For example:
  38. //
  39. // switch err := errors.Cause(err).(type) {
  40. // case *MyError:
  41. // // handle specifically
  42. // default:
  43. // // unknown error
  44. // }
  45. //
  46. // causer interface is not exported by this package, but is considered a part
  47. // of stable public API.
  48. //
  49. // Formatted printing of errors
  50. //
  51. // All error values returned from this package implement fmt.Formatter and can
  52. // be formatted by the fmt package. The following verbs are supported
  53. //
  54. // %s print the error. If the error has a Cause it will be
  55. // printed recursively
  56. // %v see %s
  57. // %+v extended format. Each Frame of the error's StackTrace will
  58. // be printed in detail.
  59. //
  60. // Retrieving the stack trace of an error or wrapper
  61. //
  62. // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
  63. // invoked. This information can be retrieved with the following interface.
  64. //
  65. // type stackTracer interface {
  66. // StackTrace() errors.StackTrace
  67. // }
  68. //
  69. // Where errors.StackTrace is defined as
  70. //
  71. // type StackTrace []Frame
  72. //
  73. // The Frame type represents a call site in the stack trace. Frame supports
  74. // the fmt.Formatter interface that can be used for printing information about
  75. // the stack trace of this error. For example:
  76. //
  77. // if err, ok := err.(stackTracer); ok {
  78. // for _, f := range err.StackTrace() {
  79. // fmt.Printf("%+s:%d", f)
  80. // }
  81. // }
  82. //
  83. // stackTracer interface is not exported by this package, but is considered a part
  84. // of stable public API.
  85. //
  86. // See the documentation for Frame.Format for more details.
  87. package errors
  88. import (
  89. "errors"
  90. "fmt"
  91. "io"
  92. )
  93. // New returns an error with the supplied message.
  94. func New(message string) error {
  95. err := errors.New(message)
  96. return &withStack{
  97. err,
  98. callers(),
  99. }
  100. }
  101. // Errorf formats according to a format specifier and returns the string
  102. // as a value that satisfies error.
  103. func Errorf(format string, args ...interface{}) error {
  104. err := fmt.Errorf(format, args...)
  105. return &withStack{
  106. err,
  107. callers(),
  108. }
  109. }
  110. type withStack struct {
  111. error
  112. *stack
  113. }
  114. func (w *withStack) Format(s fmt.State, verb rune) {
  115. switch verb {
  116. case 'v':
  117. if s.Flag('+') {
  118. io.WriteString(s, w.Error())
  119. w.stack.Format(s, verb)
  120. return
  121. }
  122. fallthrough
  123. case 's':
  124. io.WriteString(s, w.Error())
  125. }
  126. }
  127. type cause struct {
  128. cause error
  129. msg string
  130. }
  131. func (c cause) Error() string { return fmt.Sprintf("%s: %v", c.msg, c.Cause()) }
  132. func (c cause) Cause() error { return c.cause }
  133. // wrapper is an error implementation returned by Wrap and Wrapf
  134. // that implements its own fmt.Formatter.
  135. type wrapper struct {
  136. cause
  137. *stack
  138. }
  139. func (w wrapper) Format(s fmt.State, verb rune) {
  140. switch verb {
  141. case 'v':
  142. if s.Flag('+') {
  143. fmt.Fprintf(s, "%+v\n", w.Cause())
  144. io.WriteString(s, w.msg)
  145. fmt.Fprintf(s, "%+v", w.StackTrace())
  146. return
  147. }
  148. fallthrough
  149. case 's':
  150. io.WriteString(s, w.Error())
  151. case 'q':
  152. fmt.Fprintf(s, "%q", w.Error())
  153. }
  154. }
  155. // Wrap returns an error annotating err with message.
  156. // If err is nil, Wrap returns nil.
  157. func Wrap(err error, message string) error {
  158. if err == nil {
  159. return nil
  160. }
  161. return wrapper{
  162. cause: cause{
  163. cause: err,
  164. msg: message,
  165. },
  166. stack: callers(),
  167. }
  168. }
  169. // Wrapf returns an error annotating err with the format specifier.
  170. // If err is nil, Wrapf returns nil.
  171. func Wrapf(err error, format string, args ...interface{}) error {
  172. if err == nil {
  173. return nil
  174. }
  175. return wrapper{
  176. cause: cause{
  177. cause: err,
  178. msg: fmt.Sprintf(format, args...),
  179. },
  180. stack: callers(),
  181. }
  182. }
  183. // Cause returns the underlying cause of the error, if possible.
  184. // An error value has a cause if it implements the following
  185. // interface:
  186. //
  187. // type causer interface {
  188. // Cause() error
  189. // }
  190. //
  191. // If the error does not implement Cause, the original error will
  192. // be returned. If the error is nil, nil will be returned without further
  193. // investigation.
  194. func Cause(err error) error {
  195. type causer interface {
  196. Cause() error
  197. }
  198. for err != nil {
  199. cause, ok := err.(causer)
  200. if !ok {
  201. break
  202. }
  203. err = cause.Cause()
  204. }
  205. return err
  206. }