errors.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // Package errors is a drop-in replacement for Golang lib 'errors'.
  2. package errors
  3. import (
  4. "fmt"
  5. "v2ray.com/core/common/serial"
  6. )
  7. type hasInnerError interface {
  8. // Inner returns the underlying error of this one.
  9. Inner() error
  10. }
  11. type actionRequired interface {
  12. ActionRequired() bool
  13. }
  14. // Error is an error object with underlying error.
  15. type Error struct {
  16. message string
  17. inner error
  18. actionRequired bool
  19. }
  20. // Error implements error.Error().
  21. func (v Error) Error() string {
  22. msg := v.message
  23. if v.inner != nil {
  24. msg += " > " + v.inner.Error()
  25. }
  26. return msg
  27. }
  28. // Inner implements hasInnerError.Inner()
  29. func (v Error) Inner() error {
  30. if v.inner == nil {
  31. return nil
  32. }
  33. return v.inner
  34. }
  35. func (v Error) ActionRequired() bool {
  36. return v.actionRequired
  37. }
  38. func (v Error) RequireUserAction() Error {
  39. v.actionRequired = true
  40. return v
  41. }
  42. func (v Error) Message(msg ...interface{}) Error {
  43. return Error{
  44. inner: v,
  45. message: serial.Concat(msg...),
  46. }
  47. }
  48. func (v Error) Format(format string, values ...interface{}) Error {
  49. return v.Message(fmt.Sprintf(format, values...))
  50. }
  51. // New returns a new error object with message formed from given arguments.
  52. func New(msg ...interface{}) Error {
  53. return Error{
  54. message: serial.Concat(msg...),
  55. }
  56. }
  57. // Base returns an Error based on the given error.
  58. func Base(err error) Error {
  59. return Error{
  60. inner: err,
  61. }
  62. }
  63. func Format(format string, values ...interface{}) error {
  64. return New(fmt.Sprintf(format, values...))
  65. }
  66. // Cause returns the root cause of this error.
  67. func Cause(err error) error {
  68. if err == nil {
  69. return nil
  70. }
  71. for {
  72. inner, ok := err.(hasInnerError)
  73. if !ok || inner.Inner() == nil {
  74. break
  75. }
  76. err = inner.Inner()
  77. }
  78. return err
  79. }
  80. func IsActionRequired(err error) bool {
  81. for err != nil {
  82. if ar, ok := err.(actionRequired); ok && ar.ActionRequired() {
  83. return true
  84. }
  85. inner, ok := err.(hasInnerError)
  86. if !ok || inner.Inner() == nil {
  87. break
  88. }
  89. err = inner.Inner()
  90. }
  91. return false
  92. }