error.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Package errors provides errors that have stack-traces.
  2. //
  3. // This is particularly useful when you want to understand the
  4. // state of execution when an error was returned unexpectedly.
  5. //
  6. // It provides the type *Error which implements the standard
  7. // golang error interface, so you can use this library interchangably
  8. // with code that is expecting a normal error return.
  9. //
  10. // For example:
  11. //
  12. // package crashy
  13. //
  14. // import "github.com/go-errors/errors"
  15. //
  16. // var Crashed = errors.Errorf("oh dear")
  17. //
  18. // func Crash() error {
  19. // return errors.New(Crashed)
  20. // }
  21. //
  22. // This can be called as follows:
  23. //
  24. // package main
  25. //
  26. // import (
  27. // "crashy"
  28. // "fmt"
  29. // "github.com/go-errors/errors"
  30. // )
  31. //
  32. // func main() {
  33. // err := crashy.Crash()
  34. // if err != nil {
  35. // if errors.Is(err, crashy.Crashed) {
  36. // fmt.Println(err.(*errors.Error).ErrorStack())
  37. // } else {
  38. // panic(err)
  39. // }
  40. // }
  41. // }
  42. //
  43. // This package was original written to allow reporting to Bugsnag,
  44. // but after I found similar packages by Facebook and Dropbox, it
  45. // was moved to one canonical location so everyone can benefit.
  46. package errors
  47. import (
  48. "bytes"
  49. "fmt"
  50. "reflect"
  51. "runtime"
  52. )
  53. // The maximum number of stackframes on any error.
  54. var MaxStackDepth = 50
  55. // Error is an error with an attached stacktrace. It can be used
  56. // wherever the builtin error interface is expected.
  57. type Error struct {
  58. Err error
  59. stack []uintptr
  60. frames []StackFrame
  61. prefix string
  62. }
  63. // New makes an Error from the given value. If that value is already an
  64. // error then it will be used directly, if not, it will be passed to
  65. // fmt.Errorf("%v"). The stacktrace will point to the line of code that
  66. // called New.
  67. func New(e interface{}) *Error {
  68. var err error
  69. switch e := e.(type) {
  70. case error:
  71. err = e
  72. default:
  73. err = fmt.Errorf("%v", e)
  74. }
  75. stack := make([]uintptr, MaxStackDepth)
  76. length := runtime.Callers(2, stack[:])
  77. return &Error{
  78. Err: err,
  79. stack: stack[:length],
  80. }
  81. }
  82. // Wrap makes an Error from the given value. If that value is already an
  83. // error then it will be used directly, if not, it will be passed to
  84. // fmt.Errorf("%v"). The skip parameter indicates how far up the stack
  85. // to start the stacktrace. 0 is from the current call, 1 from its caller, etc.
  86. func Wrap(e interface{}, skip int) *Error {
  87. if e == nil {
  88. return nil
  89. }
  90. var err error
  91. switch e := e.(type) {
  92. case *Error:
  93. return e
  94. case error:
  95. err = e
  96. default:
  97. err = fmt.Errorf("%v", e)
  98. }
  99. stack := make([]uintptr, MaxStackDepth)
  100. length := runtime.Callers(2+skip, stack[:])
  101. return &Error{
  102. Err: err,
  103. stack: stack[:length],
  104. }
  105. }
  106. // WrapPrefix makes an Error from the given value. If that value is already an
  107. // error then it will be used directly, if not, it will be passed to
  108. // fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the
  109. // error message when calling Error(). The skip parameter indicates how far
  110. // up the stack to start the stacktrace. 0 is from the current call,
  111. // 1 from its caller, etc.
  112. func WrapPrefix(e interface{}, prefix string, skip int) *Error {
  113. if e == nil {
  114. return nil
  115. }
  116. err := Wrap(e, 1+skip)
  117. if err.prefix != "" {
  118. prefix = fmt.Sprintf("%s: %s", prefix, err.prefix)
  119. }
  120. return &Error{
  121. Err: err.Err,
  122. stack: err.stack,
  123. prefix: prefix,
  124. }
  125. }
  126. // Is detects whether the error is equal to a given error. Errors
  127. // are considered equal by this function if they are the same object,
  128. // or if they both contain the same error inside an errors.Error.
  129. func Is(e error, original error) bool {
  130. if e == original {
  131. return true
  132. }
  133. if e, ok := e.(*Error); ok {
  134. return Is(e.Err, original)
  135. }
  136. if original, ok := original.(*Error); ok {
  137. return Is(e, original.Err)
  138. }
  139. return false
  140. }
  141. // Errorf creates a new error with the given message. You can use it
  142. // as a drop-in replacement for fmt.Errorf() to provide descriptive
  143. // errors in return values.
  144. func Errorf(format string, a ...interface{}) *Error {
  145. return Wrap(fmt.Errorf(format, a...), 1)
  146. }
  147. // Error returns the underlying error's message.
  148. func (err *Error) Error() string {
  149. msg := err.Err.Error()
  150. if err.prefix != "" {
  151. msg = fmt.Sprintf("%s: %s", err.prefix, msg)
  152. }
  153. return msg
  154. }
  155. // Stack returns the callstack formatted the same way that go does
  156. // in runtime/debug.Stack()
  157. func (err *Error) Stack() []byte {
  158. buf := bytes.Buffer{}
  159. for _, frame := range err.StackFrames() {
  160. buf.WriteString(frame.String())
  161. }
  162. return buf.Bytes()
  163. }
  164. // Callers satisfies the bugsnag ErrorWithCallerS() interface
  165. // so that the stack can be read out.
  166. func (err *Error) Callers() []uintptr {
  167. return err.stack
  168. }
  169. // ErrorStack returns a string that contains both the
  170. // error message and the callstack.
  171. func (err *Error) ErrorStack() string {
  172. return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack())
  173. }
  174. // StackFrames returns an array of frames containing information about the
  175. // stack.
  176. func (err *Error) StackFrames() []StackFrame {
  177. if err.frames == nil {
  178. err.frames = make([]StackFrame, len(err.stack))
  179. for i, pc := range err.stack {
  180. err.frames[i] = NewStackFrame(pc)
  181. }
  182. }
  183. return err.frames
  184. }
  185. // TypeName returns the type this error. e.g. *errors.stringError.
  186. func (err *Error) TypeName() string {
  187. if _, ok := err.Err.(uncaughtPanic); ok {
  188. return "panic"
  189. }
  190. return reflect.TypeOf(err.Err).String()
  191. }