errors.go 6.2 KB

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