errors.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. // WithStack annotates err with a stack trace at the point WithStack was called.
  129. // If err is nil, WithStack returns nil.
  130. func WithStack(err error) error {
  131. if err == nil {
  132. return nil
  133. }
  134. return &withStack{
  135. err,
  136. callers(),
  137. }
  138. }
  139. type withStack struct {
  140. error
  141. *stack
  142. }
  143. func (w *withStack) Cause() error { return w.error }
  144. func (w *withStack) Format(s fmt.State, verb rune) {
  145. switch verb {
  146. case 'v':
  147. if s.Flag('+') {
  148. fmt.Fprintf(s, "%+v", w.Cause())
  149. w.stack.Format(s, verb)
  150. return
  151. }
  152. fallthrough
  153. case 's':
  154. io.WriteString(s, w.Error())
  155. case 'q':
  156. fmt.Fprintf(s, "%q", w.Error())
  157. }
  158. }
  159. // Wrap returns an error annotating err with message.
  160. // If err is nil, Wrap returns nil.
  161. // Wrap is conceptually the same as calling
  162. //
  163. // errors.WithStack(errors.WithMessage(err, msg))
  164. func Wrap(err error, message string) error {
  165. if err == nil {
  166. return nil
  167. }
  168. err = &withMessage{
  169. cause: err,
  170. msg: message,
  171. }
  172. return &withStack{
  173. err,
  174. callers(),
  175. }
  176. }
  177. // Wrapf returns an error annotating err with the format specifier.
  178. // If err is nil, Wrapf returns nil.
  179. // Wrapf is conceptually the same as calling
  180. //
  181. // errors.WithStack(errors.WithMessage(err, format, args...))
  182. func Wrapf(err error, format string, args ...interface{}) error {
  183. if err == nil {
  184. return nil
  185. }
  186. err = &withMessage{
  187. cause: err,
  188. msg: fmt.Sprintf(format, args...),
  189. }
  190. return &withStack{
  191. err,
  192. callers(),
  193. }
  194. }
  195. // WithMessage annotates err with a new message.
  196. // If err is nil, WithStack returns nil.
  197. func WithMessage(err error, message string) error {
  198. if err == nil {
  199. return nil
  200. }
  201. return &withMessage{
  202. cause: err,
  203. msg: message,
  204. }
  205. }
  206. type withMessage struct {
  207. cause error
  208. msg string
  209. }
  210. func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
  211. func (w *withMessage) Cause() error { return w.cause }
  212. func (w *withMessage) Format(s fmt.State, verb rune) {
  213. switch verb {
  214. case 'v':
  215. if s.Flag('+') {
  216. fmt.Fprintf(s, "%+v\n", w.Cause())
  217. io.WriteString(s, w.msg)
  218. return
  219. }
  220. fallthrough
  221. case 's', 'q':
  222. io.WriteString(s, w.Error())
  223. }
  224. }
  225. // Cause returns the underlying cause of the error, if possible.
  226. // An error value has a cause if it implements the following
  227. // interface:
  228. //
  229. // type causer interface {
  230. // Cause() error
  231. // }
  232. //
  233. // If the error does not implement Cause, the original error will
  234. // be returned. If the error is nil, nil will be returned without further
  235. // investigation.
  236. func Cause(err error) error {
  237. type causer interface {
  238. Cause() error
  239. }
  240. for err != nil {
  241. cause, ok := err.(causer)
  242. if !ok {
  243. break
  244. }
  245. err = cause.Cause()
  246. }
  247. return err
  248. }