errors.go 6.1 KB

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