errors.go 5.8 KB

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