errors.go 6.2 KB

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