errors.go 6.0 KB

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