errors.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 stack trace of an error or wrapper
  25. //
  26. // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
  27. // invoked. This information can be retrieved with the following interface.
  28. //
  29. // type Stack interface {
  30. // Stack() []uintptr
  31. // }
  32. //
  33. // Retrieving the cause of an error
  34. //
  35. // Using errors.Wrap constructs a stack of errors, adding context to the
  36. // preceding error. Depending on the nature of the error it may be necessary
  37. // to reverse the operation of errors.Wrap to retrieve the original error
  38. // for inspection. Any error value which implements this interface
  39. //
  40. // type Causer interface {
  41. // Cause() error
  42. // }
  43. //
  44. // can be inspected by errors.Cause. errors.Cause will recursively retrieve
  45. // the topmost error which does not implement causer, which is assumed to be
  46. // the original cause. For example:
  47. //
  48. // switch err := errors.Cause(err).(type) {
  49. // case *MyError:
  50. // // handle specifically
  51. // default:
  52. // // unknown error
  53. // }
  54. package errors
  55. import (
  56. "errors"
  57. "fmt"
  58. "io"
  59. "runtime"
  60. "strings"
  61. )
  62. // stack represents a stack of programm counters.
  63. type stack []uintptr
  64. func (s *stack) Stack() []uintptr { return *s }
  65. func (s *stack) Location() (string, int) {
  66. return location((*s)[0] - 1)
  67. }
  68. // New returns an error that formats as the given text.
  69. func New(text string) error {
  70. return struct {
  71. error
  72. *stack
  73. }{
  74. errors.New(text),
  75. callers(),
  76. }
  77. }
  78. type cause struct {
  79. cause error
  80. message string
  81. }
  82. func (c cause) Error() string { return c.Message() + ": " + c.Cause().Error() }
  83. func (c cause) Cause() error { return c.cause }
  84. func (c cause) Message() string { return c.message }
  85. // Errorf formats according to a format specifier and returns the string
  86. // as a value that satisfies error.
  87. func Errorf(format string, args ...interface{}) error {
  88. return struct {
  89. error
  90. *stack
  91. }{
  92. fmt.Errorf(format, args...),
  93. callers(),
  94. }
  95. }
  96. // Wrap returns an error annotating the cause with message.
  97. // If cause is nil, Wrap returns nil.
  98. func Wrap(cause error, message string) error {
  99. if cause == nil {
  100. return nil
  101. }
  102. return wrap(cause, message, callers())
  103. }
  104. // Wrapf returns an error annotating the cause with the format specifier.
  105. // If cause is nil, Wrapf returns nil.
  106. func Wrapf(cause error, format string, args ...interface{}) error {
  107. if cause == nil {
  108. return nil
  109. }
  110. return wrap(cause, fmt.Sprintf(format, args...), callers())
  111. }
  112. func wrap(err error, msg string, st *stack) error {
  113. return struct {
  114. cause
  115. *stack
  116. }{
  117. cause{
  118. cause: err,
  119. message: msg,
  120. },
  121. st,
  122. }
  123. }
  124. type causer interface {
  125. Cause() error
  126. }
  127. // Cause returns the underlying cause of the error, if possible.
  128. // An error value has a cause if it implements the following
  129. // interface:
  130. //
  131. // type Causer interface {
  132. // Cause() error
  133. // }
  134. //
  135. // If the error does not implement Cause, the original error will
  136. // be returned. If the error is nil, nil will be returned without further
  137. // investigation.
  138. func Cause(err error) error {
  139. for err != nil {
  140. cause, ok := err.(causer)
  141. if !ok {
  142. break
  143. }
  144. err = cause.Cause()
  145. }
  146. return err
  147. }
  148. // Fprint prints the error to the supplied writer.
  149. // If the error implements the Causer interface described in Cause
  150. // Print will recurse into the error's cause.
  151. // If the error implements the inteface:
  152. //
  153. // type Location interface {
  154. // Location() (file string, line int)
  155. // }
  156. //
  157. // Print will also print the file and line of the error.
  158. // If err is nil, nothing is printed.
  159. func Fprint(w io.Writer, err error) {
  160. type location interface {
  161. Location() (string, int)
  162. }
  163. type message interface {
  164. Message() string
  165. }
  166. for err != nil {
  167. if err, ok := err.(location); ok {
  168. file, line := err.Location()
  169. fmt.Fprintf(w, "%s:%d: ", file, line)
  170. }
  171. switch err := err.(type) {
  172. case message:
  173. fmt.Fprintln(w, err.Message())
  174. default:
  175. fmt.Fprintln(w, err.Error())
  176. }
  177. cause, ok := err.(causer)
  178. if !ok {
  179. break
  180. }
  181. err = cause.Cause()
  182. }
  183. }
  184. func callers() *stack {
  185. const depth = 32
  186. var pcs [depth]uintptr
  187. n := runtime.Callers(3, pcs[:])
  188. var st stack = pcs[0:n]
  189. return &st
  190. }
  191. // location returns the source file and line matching pc.
  192. func location(pc uintptr) (string, int) {
  193. fn := runtime.FuncForPC(pc)
  194. if fn == nil {
  195. return "unknown", 0
  196. }
  197. file, line := fn.FileLine(pc)
  198. // Here we want to get the source file path relative to the compile time
  199. // GOPATH. As of Go 1.6.x there is no direct way to know the compiled
  200. // GOPATH at runtime, but we can infer the number of path segments in the
  201. // GOPATH. We note that fn.Name() returns the function name qualified by
  202. // the import path, which does not include the GOPATH. Thus we can trim
  203. // segments from the beginning of the file path until the number of path
  204. // separators remaining is one more than the number of path separators in
  205. // the function name. For example, given:
  206. //
  207. // GOPATH /home/user
  208. // file /home/user/src/pkg/sub/file.go
  209. // fn.Name() pkg/sub.Type.Method
  210. //
  211. // We want to produce:
  212. //
  213. // pkg/sub/file.go
  214. //
  215. // From this we can easily see that fn.Name() has one less path separator
  216. // than our desired output. We count separators from the end of the file
  217. // path until it finds two more than in the function name and then move
  218. // one character forward to preserve the initial path segment without a
  219. // leading separator.
  220. const sep = "/"
  221. goal := strings.Count(fn.Name(), sep) + 2
  222. i := len(file)
  223. for n := 0; n < goal; n++ {
  224. i = strings.LastIndex(file[:i], sep)
  225. if i == -1 {
  226. // not enough separators found, set i so that the slice expression
  227. // below leaves file unmodified
  228. i = -len(sep)
  229. break
  230. }
  231. }
  232. // get back to 0 or trim the leading separator
  233. file = file[i+len(sep):]
  234. return file, line
  235. }