errors.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.Annotate function returns a new error that adds context to the
  17. // original error by recording a stack trace at the point Annotate is called,
  18. // and the supplied message. For example
  19. //
  20. // _, err := ioutil.ReadAll(r)
  21. // if err != nil {
  22. // return errors.Annotate(err, "read failed")
  23. // }
  24. //
  25. // If additional control is required the errors.AddStack and errors.WithMessage
  26. // functions destructure errors.Annotate into its component operations of annotating
  27. // an error with a stack trace and an a message, respectively.
  28. //
  29. // Retrieving the cause of an error
  30. //
  31. // Using errors.Annotate constructs a stack of errors, adding context to the
  32. // preceding error. Depending on the nature of the error it may be necessary
  33. // to reverse the operation of errors.Annotate to retrieve the original error
  34. // for inspection. Any error value which implements this interface
  35. //
  36. // type causer interface {
  37. // Cause() error
  38. // }
  39. //
  40. // can be inspected by errors.Cause. errors.Cause will recursively retrieve
  41. // the topmost error which does not implement causer, which is assumed to be
  42. // the original cause. For example:
  43. //
  44. // switch err := errors.Cause(err).(type) {
  45. // case *MyError:
  46. // // handle specifically
  47. // default:
  48. // // unknown error
  49. // }
  50. //
  51. // causer interface is not exported by this package, but is considered a part
  52. // of stable public API.
  53. // errors.Unwrap is also available: this will retrieve the next error in the chain.
  54. //
  55. // Formatted printing of errors
  56. //
  57. // All error values returned from this package implement fmt.Formatter and can
  58. // be formatted by the fmt package. The following verbs are supported
  59. //
  60. // %s print the error. If the error has a Cause it will be
  61. // printed recursively
  62. // %v see %s
  63. // %+v extended format. Each Frame of the error's StackTrace will
  64. // be printed in detail.
  65. //
  66. // Retrieving the stack trace of an error or wrapper
  67. //
  68. // New, Errorf, Annotate, and Annotatef record a stack trace at the point they are invoked.
  69. // This information can be retrieved with the StackTracer interface that returns
  70. // a StackTrace. Where errors.StackTrace is defined as
  71. //
  72. // type StackTrace []Frame
  73. //
  74. // The Frame type represents a call site in the stack trace. Frame supports
  75. // the fmt.Formatter interface that can be used for printing information about
  76. // the stack trace of this error. For example:
  77. //
  78. // if stacked := errors.GetStackTracer(err); stacked != nil {
  79. // for _, f := range stacked.StackTrace() {
  80. // fmt.Printf("%+s:%d", f)
  81. // }
  82. // }
  83. //
  84. // See the documentation for Frame.Format for more details.
  85. //
  86. // errors.Find can be used to search for an error in the error chain.
  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. // StackTraceAware is an optimization to avoid repetitive traversals of an error chain.
  110. // HasStack checks for this marker first.
  111. // Annotate/Wrap and Annotatef/Wrapf will produce this marker.
  112. type StackTraceAware interface {
  113. HasStack() bool
  114. }
  115. // HasStack tells whether a StackTracer exists in the error chain
  116. func HasStack(err error) bool {
  117. if errWithStack, ok := err.(StackTraceAware); ok {
  118. return errWithStack.HasStack()
  119. }
  120. return GetStackTracer(err) != nil
  121. }
  122. // fundamental is an error that has a message and a stack, but no caller.
  123. type fundamental struct {
  124. msg string
  125. *stack
  126. }
  127. func (f *fundamental) Error() string { return f.msg }
  128. func (f *fundamental) Format(s fmt.State, verb rune) {
  129. switch verb {
  130. case 'v':
  131. if s.Flag('+') {
  132. io.WriteString(s, f.msg)
  133. f.stack.Format(s, verb)
  134. return
  135. }
  136. fallthrough
  137. case 's':
  138. io.WriteString(s, f.msg)
  139. case 'q':
  140. fmt.Fprintf(s, "%q", f.msg)
  141. }
  142. }
  143. // WithStack annotates err with a stack trace at the point WithStack was called.
  144. // If err is nil, WithStack returns nil.
  145. //
  146. // For most use cases this is deprecated and AddStack should be used (which will ensure just one stack trace).
  147. // However, one may want to use this in some situations, for example to create a 2nd trace across a goroutine.
  148. func WithStack(err error) error {
  149. if err == nil {
  150. return nil
  151. }
  152. return &withStack{
  153. err,
  154. callers(),
  155. }
  156. }
  157. // AddStack is similar to WithStack.
  158. // However, it will first check with HasStack to see if a stack trace already exists in the causer chain before creating another one.
  159. func AddStack(err error) error {
  160. if HasStack(err) {
  161. return err
  162. }
  163. return WithStack(err)
  164. }
  165. type withStack struct {
  166. error
  167. *stack
  168. }
  169. func (w *withStack) Cause() error { return w.error }
  170. func (w *withStack) Format(s fmt.State, verb rune) {
  171. switch verb {
  172. case 'v':
  173. if s.Flag('+') {
  174. fmt.Fprintf(s, "%+v", w.Cause())
  175. w.stack.Format(s, verb)
  176. return
  177. }
  178. fallthrough
  179. case 's':
  180. io.WriteString(s, w.Error())
  181. case 'q':
  182. fmt.Fprintf(s, "%q", w.Error())
  183. }
  184. }
  185. // Wrap returns an error annotating err with a stack trace
  186. // at the point Wrap is called, and the supplied message.
  187. // If err is nil, Wrap returns nil.
  188. //
  189. // For most use cases this is deprecated in favor of Annotate.
  190. // Annotate avoids creating duplicate stack traces.
  191. func Wrap(err error, message string) error {
  192. if err == nil {
  193. return nil
  194. }
  195. hasStack := HasStack(err)
  196. err = &withMessage{
  197. cause: err,
  198. msg: message,
  199. causeHasStack: hasStack,
  200. }
  201. return &withStack{
  202. err,
  203. callers(),
  204. }
  205. }
  206. // Wrapf returns an error annotating err with a stack trace
  207. // at the point Wrapf is call, and the format specifier.
  208. // If err is nil, Wrapf returns nil.
  209. //
  210. // For most use cases this is deprecated in favor of Annotatef.
  211. // Annotatef avoids creating duplicate stack traces.
  212. func Wrapf(err error, format string, args ...interface{}) error {
  213. if err == nil {
  214. return nil
  215. }
  216. hasStack := HasStack(err)
  217. err = &withMessage{
  218. cause: err,
  219. msg: fmt.Sprintf(format, args...),
  220. causeHasStack: hasStack,
  221. }
  222. return &withStack{
  223. err,
  224. callers(),
  225. }
  226. }
  227. // WithMessage annotates err with a new message.
  228. // If err is nil, WithMessage returns nil.
  229. func WithMessage(err error, message string) error {
  230. if err == nil {
  231. return nil
  232. }
  233. return &withMessage{
  234. cause: err,
  235. msg: message,
  236. causeHasStack: HasStack(err),
  237. }
  238. }
  239. type withMessage struct {
  240. cause error
  241. msg string
  242. causeHasStack bool
  243. }
  244. func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
  245. func (w *withMessage) Cause() error { return w.cause }
  246. func (w *withMessage) HasStack() bool { return w.causeHasStack }
  247. func (w *withMessage) Format(s fmt.State, verb rune) {
  248. switch verb {
  249. case 'v':
  250. if s.Flag('+') {
  251. fmt.Fprintf(s, "%+v\n", w.Cause())
  252. io.WriteString(s, w.msg)
  253. return
  254. }
  255. fallthrough
  256. case 's', 'q':
  257. io.WriteString(s, w.Error())
  258. }
  259. }
  260. // Cause returns the underlying cause of the error, if possible.
  261. // An error value has a cause if it implements the following
  262. // interface:
  263. //
  264. // type causer interface {
  265. // Cause() error
  266. // }
  267. //
  268. // If the error does not implement Cause, the original error will
  269. // be returned. If the error is nil, nil will be returned without further
  270. // investigation.
  271. func Cause(err error) error {
  272. cause := Unwrap(err)
  273. if cause == nil {
  274. return err
  275. }
  276. return Cause(cause)
  277. }
  278. // Unwrap uses causer to return the next error in the chain or nil.
  279. // This goes one-level deeper, whereas Cause goes as far as possible
  280. func Unwrap(err error) error {
  281. type causer interface {
  282. Cause() error
  283. }
  284. if unErr, ok := err.(causer); ok {
  285. return unErr.Cause()
  286. }
  287. return nil
  288. }
  289. // Find an error in the chain that matches a test function.
  290. // returns nil if no error is found.
  291. func Find(origErr error, test func(error) bool) error {
  292. var foundErr error
  293. WalkDeep(origErr, func(err error) bool {
  294. if test(err) {
  295. foundErr = err
  296. return true
  297. }
  298. return false
  299. })
  300. return foundErr
  301. }