errors.go 6.3 KB

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