errors.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 program 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 err with message.
  97. // If err is nil, Wrap returns nil.
  98. func Wrap(err error, message string) error {
  99. if err == nil {
  100. return nil
  101. }
  102. return struct {
  103. cause
  104. *stack
  105. }{
  106. cause{
  107. cause: err,
  108. message: message,
  109. },
  110. callers(),
  111. }
  112. }
  113. // Wrapf returns an error annotating err with the format specifier.
  114. // If err is nil, Wrapf returns nil.
  115. func Wrapf(err error, format string, args ...interface{}) error {
  116. if err == nil {
  117. return nil
  118. }
  119. return struct {
  120. cause
  121. *stack
  122. }{
  123. cause{
  124. cause: err,
  125. message: fmt.Sprintf(format, args...),
  126. },
  127. callers(),
  128. }
  129. }
  130. type causer interface {
  131. Cause() error
  132. }
  133. // Cause returns the underlying cause of the error, if possible.
  134. // An error value has a cause if it implements the following
  135. // interface:
  136. //
  137. // type Causer interface {
  138. // Cause() error
  139. // }
  140. //
  141. // If the error does not implement Cause, the original error will
  142. // be returned. If the error is nil, nil will be returned without further
  143. // investigation.
  144. func Cause(err error) error {
  145. for err != nil {
  146. cause, ok := err.(causer)
  147. if !ok {
  148. break
  149. }
  150. err = cause.Cause()
  151. }
  152. return err
  153. }
  154. // Fprint prints the error to the supplied writer.
  155. // If the error implements the Causer interface described in Cause
  156. // Print will recurse into the error's cause.
  157. // If the error implements the inteface:
  158. //
  159. // type Location interface {
  160. // Location() (file string, line int)
  161. // }
  162. //
  163. // Print will also print the file and line of the error.
  164. // If err is nil, nothing is printed.
  165. func Fprint(w io.Writer, err error) {
  166. type location interface {
  167. Location() (string, int)
  168. }
  169. type message interface {
  170. Message() string
  171. }
  172. for err != nil {
  173. if err, ok := err.(location); ok {
  174. file, line := err.Location()
  175. fmt.Fprintf(w, "%s:%d: ", file, line)
  176. }
  177. switch err := err.(type) {
  178. case message:
  179. fmt.Fprintln(w, err.Message())
  180. default:
  181. fmt.Fprintln(w, err.Error())
  182. }
  183. cause, ok := err.(causer)
  184. if !ok {
  185. break
  186. }
  187. err = cause.Cause()
  188. }
  189. }
  190. func callers() *stack {
  191. const depth = 32
  192. var pcs [depth]uintptr
  193. n := runtime.Callers(3, pcs[:])
  194. var st stack = pcs[0:n]
  195. return &st
  196. }
  197. // location returns the source file and line matching pc.
  198. func location(pc uintptr) (string, int) {
  199. fn := runtime.FuncForPC(pc)
  200. if fn == nil {
  201. return "unknown", 0
  202. }
  203. // Here we want to get the source file path relative to the compile time
  204. // GOPATH. As of Go 1.6.x there is no direct way to know the compiled
  205. // GOPATH at runtime, but we can infer the number of path segments in the
  206. // GOPATH. We note that fn.Name() returns the function name qualified by
  207. // the import path, which does not include the GOPATH. Thus we can trim
  208. // segments from the beginning of the file path until the number of path
  209. // separators remaining is one more than the number of path separators in
  210. // the function name. For example, given:
  211. //
  212. // GOPATH /home/user
  213. // file /home/user/src/pkg/sub/file.go
  214. // fn.Name() pkg/sub.Type.Method
  215. //
  216. // We want to produce:
  217. //
  218. // pkg/sub/file.go
  219. //
  220. // From this we can easily see that fn.Name() has one less path separator
  221. // than our desired output. We count separators from the end of the file
  222. // path until it finds two more than in the function name and then move
  223. // one character forward to preserve the initial path segment without a
  224. // leading separator.
  225. const sep = "/"
  226. goal := strings.Count(fn.Name(), sep) + 2
  227. file, line := fn.FileLine(pc)
  228. i := len(file)
  229. for n := 0; n < goal; n++ {
  230. i = strings.LastIndex(file[:i], sep)
  231. if i == -1 {
  232. // not enough separators found, set i so that the slice expression
  233. // below leaves file unmodified
  234. i = -len(sep)
  235. break
  236. }
  237. }
  238. // get back to 0 or trim the leading separator
  239. file = file[i+len(sep):]
  240. return file, line
  241. }