errors.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. "fmt"
  90. "io"
  91. )
  92. // New returns an error with the supplied message.
  93. // New also records the stack trace at the point it was called.
  94. func New(message string) error {
  95. return &fundamental{
  96. msg: message,
  97. stack: callers(),
  98. }
  99. }
  100. // Errorf formats according to a format specifier and returns the string
  101. // as a value that satisfies error.
  102. // Errorf also records the stack trace at the point it was called.
  103. func Errorf(format string, args ...interface{}) error {
  104. return &fundamental{
  105. msg: fmt.Sprintf(format, args...),
  106. stack: callers(),
  107. }
  108. }
  109. // fundamental is an error that has a message and a stack, but no caller.
  110. type fundamental struct {
  111. msg string
  112. *stack
  113. }
  114. func (f *fundamental) Error() string { return f.msg }
  115. func (f *fundamental) Format(s fmt.State, verb rune) {
  116. switch verb {
  117. case 'v':
  118. if s.Flag('+') {
  119. io.WriteString(s, f.msg)
  120. f.stack.Format(s, verb)
  121. return
  122. }
  123. fallthrough
  124. case 's', 'q':
  125. io.WriteString(s, f.msg)
  126. }
  127. }
  128. type withStack struct {
  129. error
  130. *stack
  131. }
  132. func (w *withStack) Cause() error { return w.error }
  133. func (w *withStack) Format(s fmt.State, verb rune) {
  134. switch verb {
  135. case 'v':
  136. if s.Flag('+') {
  137. fmt.Fprintf(s, "%+v", w.Cause())
  138. w.stack.Format(s, verb)
  139. return
  140. }
  141. fallthrough
  142. case 's':
  143. io.WriteString(s, w.Error())
  144. case 'q':
  145. fmt.Fprintf(s, "%q", w.Error())
  146. }
  147. }
  148. // Wrap returns an error annotating err with message.
  149. // If err is nil, Wrap returns nil.
  150. // Wrap is conceptually the same as calling
  151. //
  152. // errors.WithStack(errors.WithMessage(err, msg))
  153. func Wrap(err error, message string) error {
  154. if err == nil {
  155. return nil
  156. }
  157. err = &withMessage{
  158. cause: err,
  159. msg: message,
  160. }
  161. return &withStack{
  162. err,
  163. callers(),
  164. }
  165. }
  166. // Wrapf returns an error annotating err with the format specifier.
  167. // If err is nil, Wrapf returns nil.
  168. // Wrapf is conceptually the same as calling
  169. //
  170. // errors.WithStack(errors.WithMessage(err, format, args...))
  171. func Wrapf(err error, format string, args ...interface{}) error {
  172. if err == nil {
  173. return nil
  174. }
  175. err = &withMessage{
  176. cause: err,
  177. msg: fmt.Sprintf(format, args...),
  178. }
  179. return &withStack{
  180. err,
  181. callers(),
  182. }
  183. }
  184. type withMessage struct {
  185. cause error
  186. msg string
  187. }
  188. func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
  189. func (w *withMessage) Cause() error { return w.cause }
  190. func (w *withMessage) Format(s fmt.State, verb rune) {
  191. switch verb {
  192. case 'v':
  193. if s.Flag('+') {
  194. fmt.Fprintf(s, "%+v\n", w.Cause())
  195. io.WriteString(s, w.msg)
  196. return
  197. }
  198. fallthrough
  199. case 's', 'q':
  200. io.WriteString(s, w.Error())
  201. }
  202. }
  203. // Cause returns the underlying cause of the error, if possible.
  204. // An error value has a cause if it implements the following
  205. // interface:
  206. //
  207. // type causer interface {
  208. // Cause() error
  209. // }
  210. //
  211. // If the error does not implement Cause, the original error will
  212. // be returned. If the error is nil, nil will be returned without further
  213. // investigation.
  214. func Cause(err error) error {
  215. type causer interface {
  216. Cause() error
  217. }
  218. for err != nil {
  219. cause, ok := err.(causer)
  220. if !ok {
  221. break
  222. }
  223. err = cause.Cause()
  224. }
  225. return err
  226. }