errors.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 when 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 by recording a stack trace at the point Wrap is called,
  18. // together with the supplied message. For example
  19. //
  20. // _, err := ioutil.ReadAll(r)
  21. // if err != nil {
  22. // return errors.Wrap(err, "read failed")
  23. // }
  24. //
  25. // If additional control is required, the errors.WithStack and
  26. // errors.WithMessage functions destructure errors.Wrap into its component
  27. // operations: annotating an error with a stack trace and with a message,
  28. // respectively.
  29. //
  30. // Retrieving the cause of an error
  31. //
  32. // Using errors.Wrap constructs a stack of errors, adding context to the
  33. // preceding error. Depending on the nature of the error it may be necessary
  34. // to reverse the operation of errors.Wrap to retrieve the original error
  35. // for inspection. Any error value which implements this interface
  36. //
  37. // type causer interface {
  38. // Cause() error
  39. // }
  40. //
  41. // can be inspected by errors.Cause. errors.Cause will recursively retrieve
  42. // the topmost error that does not implement causer, which is assumed to be
  43. // the original cause. For example:
  44. //
  45. // switch err := errors.Cause(err).(type) {
  46. // case *MyError:
  47. // // handle specifically
  48. // default:
  49. // // unknown error
  50. // }
  51. //
  52. // Although the causer interface is not exported by this package, it is
  53. // considered a part of its stable public interface.
  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, Wrap, and Wrapf record a stack trace at the point they are
  69. // invoked. This information can be retrieved with the following interface:
  70. //
  71. // type stackTracer interface {
  72. // StackTrace() errors.StackTrace
  73. // }
  74. //
  75. // The returned errors.StackTrace type is defined as
  76. //
  77. // type StackTrace []Frame
  78. //
  79. // The Frame type represents a call site in the stack trace. Frame supports
  80. // the fmt.Formatter interface that can be used for printing information about
  81. // the stack trace of this error. For example:
  82. //
  83. // if err, ok := err.(stackTracer); ok {
  84. // for _, f := range err.StackTrace() {
  85. // fmt.Printf("%+s:%d\n", f, f)
  86. // }
  87. // }
  88. //
  89. // Although the stackTracer interface is not exported by this package, it is
  90. // considered a part of its stable public interface.
  91. //
  92. // See the documentation for Frame.Format for more details.
  93. package errors
  94. import (
  95. "fmt"
  96. "io"
  97. )
  98. // New returns an error with the supplied message.
  99. // New also records the stack trace at the point it was called.
  100. func New(message string) error {
  101. return &fundamental{
  102. msg: message,
  103. stack: callers(),
  104. }
  105. }
  106. // Errorf formats according to a format specifier and returns the string
  107. // as a value that satisfies error.
  108. // Errorf also records the stack trace at the point it was called.
  109. func Errorf(format string, args ...interface{}) error {
  110. return &fundamental{
  111. msg: fmt.Sprintf(format, args...),
  112. stack: callers(),
  113. }
  114. }
  115. // fundamental is an error that has a message and a stack, but no caller.
  116. type fundamental struct {
  117. msg string
  118. *stack
  119. }
  120. func (f *fundamental) Error() string { return f.msg }
  121. func (f *fundamental) Format(s fmt.State, verb rune) {
  122. switch verb {
  123. case 'v':
  124. if s.Flag('+') {
  125. io.WriteString(s, f.msg)
  126. f.stack.Format(s, verb)
  127. return
  128. }
  129. fallthrough
  130. case 's':
  131. io.WriteString(s, f.msg)
  132. case 'q':
  133. fmt.Fprintf(s, "%q", f.msg)
  134. }
  135. }
  136. // WithStack annotates err with a stack trace at the point WithStack was called.
  137. // If err is nil, WithStack returns nil.
  138. func WithStack(err error) error {
  139. if err == nil {
  140. return nil
  141. }
  142. return &withStack{
  143. err,
  144. callers(),
  145. }
  146. }
  147. type withStack struct {
  148. error
  149. *stack
  150. }
  151. func (w *withStack) Cause() error { return w.error }
  152. // Unwrap provides compatibility for Go 1.13 error chains.
  153. func (w *withStack) Unwrap() error { return w.error }
  154. func (w *withStack) Format(s fmt.State, verb rune) {
  155. switch verb {
  156. case 'v':
  157. if s.Flag('+') {
  158. fmt.Fprintf(s, "%+v", w.Cause())
  159. w.stack.Format(s, verb)
  160. return
  161. }
  162. fallthrough
  163. case 's':
  164. io.WriteString(s, w.Error())
  165. case 'q':
  166. fmt.Fprintf(s, "%q", w.Error())
  167. }
  168. }
  169. // Wrap returns an error annotating err with a stack trace
  170. // at the point Wrap is called, and the supplied message.
  171. // If err is nil, Wrap returns nil.
  172. func Wrap(err error, message string) error {
  173. if err == nil {
  174. return nil
  175. }
  176. err = &withMessage{
  177. cause: err,
  178. msg: message,
  179. }
  180. return &withStack{
  181. err,
  182. callers(),
  183. }
  184. }
  185. // Wrapf returns an error annotating err with a stack trace
  186. // at the point Wrapf is called, and the format specifier.
  187. // If err is nil, Wrapf returns nil.
  188. func Wrapf(err error, format string, args ...interface{}) error {
  189. if err == nil {
  190. return nil
  191. }
  192. err = &withMessage{
  193. cause: err,
  194. msg: fmt.Sprintf(format, args...),
  195. }
  196. return &withStack{
  197. err,
  198. callers(),
  199. }
  200. }
  201. // WithMessage annotates err with a new message.
  202. // If err is nil, WithMessage returns nil.
  203. func WithMessage(err error, message string) error {
  204. if err == nil {
  205. return nil
  206. }
  207. return &withMessage{
  208. cause: err,
  209. msg: message,
  210. }
  211. }
  212. // WithMessagef annotates err with the format specifier.
  213. // If err is nil, WithMessagef returns nil.
  214. func WithMessagef(err error, format string, args ...interface{}) error {
  215. if err == nil {
  216. return nil
  217. }
  218. return &withMessage{
  219. cause: err,
  220. msg: fmt.Sprintf(format, args...),
  221. }
  222. }
  223. type withMessage struct {
  224. cause error
  225. msg string
  226. }
  227. func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
  228. func (w *withMessage) Cause() error { return w.cause }
  229. // Unwrap provides compatibility for Go 1.13 error chains.
  230. func (w *withMessage) Unwrap() error { return w.cause }
  231. func (w *withMessage) Format(s fmt.State, verb rune) {
  232. switch verb {
  233. case 'v':
  234. if s.Flag('+') {
  235. fmt.Fprintf(s, "%+v\n", w.Cause())
  236. io.WriteString(s, w.msg)
  237. return
  238. }
  239. fallthrough
  240. case 's', 'q':
  241. io.WriteString(s, w.Error())
  242. }
  243. }
  244. // Cause returns the underlying cause of the error, if possible.
  245. // An error value has a cause if it implements the following
  246. // interface:
  247. //
  248. // type causer interface {
  249. // Cause() error
  250. // }
  251. //
  252. // If the error does not implement Cause, the original error will
  253. // be returned. If the error is nil, nil will be returned without further
  254. // investigation.
  255. func Cause(err error) error {
  256. type causer interface {
  257. Cause() error
  258. }
  259. for err != nil {
  260. cause, ok := err.(causer)
  261. if !ok {
  262. break
  263. }
  264. err = cause.Cause()
  265. }
  266. return err
  267. }