error.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. var err error
  88. switch e := e.(type) {
  89. case *Error:
  90. return e
  91. case error:
  92. err = e
  93. default:
  94. err = fmt.Errorf("%v", e)
  95. }
  96. stack := make([]uintptr, MaxStackDepth)
  97. length := runtime.Callers(2+skip, stack[:])
  98. return &Error{
  99. Err: err,
  100. stack: stack[:length],
  101. }
  102. }
  103. // WrapPrefix makes an Error from the given value. If that value is already an
  104. // error then it will be used directly, if not, it will be passed to
  105. // fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the
  106. // error message when calling Error(). The skip parameter indicates how far
  107. // up the stack to start the stacktrace. 0 is from the current call,
  108. // 1 from its caller, etc.
  109. func WrapPrefix(e interface{}, prefix string, skip int) *Error {
  110. err := Wrap(e, skip)
  111. if err.prefix != "" {
  112. err.prefix = fmt.Sprintf("%s: %s", prefix, err.prefix)
  113. } else {
  114. err.prefix = prefix
  115. }
  116. return err
  117. }
  118. // Is detects whether the error is equal to a given error. Errors
  119. // are considered equal by this function if they are the same object,
  120. // or if they both contain the same error inside an errors.Error.
  121. func Is(e error, original error) bool {
  122. if e == original {
  123. return true
  124. }
  125. if e, ok := e.(*Error); ok {
  126. return Is(e.Err, original)
  127. }
  128. if original, ok := original.(*Error); ok {
  129. return Is(e, original.Err)
  130. }
  131. return false
  132. }
  133. // Errorf creates a new error with the given message. You can use it
  134. // as a drop-in replacement for fmt.Errorf() to provide descriptive
  135. // errors in return values.
  136. func Errorf(format string, a ...interface{}) *Error {
  137. return Wrap(fmt.Errorf(format, a...), 1)
  138. }
  139. // Error returns the underlying error's message.
  140. func (err *Error) Error() string {
  141. msg := err.Err.Error()
  142. if err.prefix != "" {
  143. msg = fmt.Sprintf("%s: %s", err.prefix, msg)
  144. }
  145. return msg
  146. }
  147. // Stack returns the callstack formatted the same way that go does
  148. // in runtime/debug.Stack()
  149. func (err *Error) Stack() []byte {
  150. buf := bytes.Buffer{}
  151. for _, frame := range err.StackFrames() {
  152. buf.WriteString(frame.String())
  153. }
  154. return buf.Bytes()
  155. }
  156. // Callers satisfies the bugsnag ErrorWithCallerS() interface
  157. // so that the stack can be read out.
  158. func (err *Error) Callers() []uintptr {
  159. return err.stack
  160. }
  161. // ErrorStack returns a string that contains both the
  162. // error message and the callstack.
  163. func (err *Error) ErrorStack() string {
  164. return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack())
  165. }
  166. // StackFrames returns an array of frames containing information about the
  167. // stack.
  168. func (err *Error) StackFrames() []StackFrame {
  169. if err.frames == nil {
  170. err.frames = make([]StackFrame, len(err.stack))
  171. for i, pc := range err.stack {
  172. err.frames[i] = NewStackFrame(pc)
  173. }
  174. }
  175. return err.frames
  176. }
  177. // TypeName returns the type this error. e.g. *errors.stringError.
  178. func (err *Error) TypeName() string {
  179. if _, ok := err.Err.(uncaughtPanic); ok {
  180. return "panic"
  181. }
  182. return reflect.TypeOf(err.Err).String()
  183. }