errors.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package errors
  2. import (
  3. "fmt"
  4. )
  5. type WTError interface {
  6. /* 标记类操作 */
  7. error
  8. WTError_TAG() // 标记
  9. /* 访问类操作 */
  10. Class() WTErrorClass
  11. Code() string
  12. Msg() string
  13. Message() string
  14. MessageWithStack() string
  15. Stack() string
  16. Cause() error
  17. /* 设置类操作 */
  18. SetCode(code string) WTError
  19. SetCodeForce(code string) WTError
  20. SetCause(cause error) WTError
  21. SetCauseForce(cause error) WTError
  22. Warp(format string, a ...any) WTError
  23. }
  24. type wtError struct {
  25. cause error
  26. msg string
  27. code string
  28. stack string
  29. class WTErrorClass
  30. }
  31. func (*wtError) WTError_TAG() {}
  32. func (w *wtError) Class() WTErrorClass {
  33. return w.class
  34. }
  35. func (w *wtError) Code() string {
  36. return w.code
  37. }
  38. func (w *wtError) Msg() string {
  39. return w.msg
  40. }
  41. func (w *wtError) Message() string {
  42. if w.cause == nil {
  43. return fmt.Sprintf("[%s] %s", w.code, w.msg)
  44. }
  45. var cause *wtError
  46. ok := As(w.cause, &cause)
  47. if ok {
  48. return fmt.Sprintf("[%s] %s: %s", w.code, w.msg, cause.Message())
  49. }
  50. return fmt.Sprintf("[%s] %s: %s", w.code, w.msg, w.cause.Error())
  51. }
  52. func (w *wtError) MessageWithStack() string {
  53. if w.cause == nil {
  54. return fmt.Sprintf("[%s]%s\n%s", w.code, w.msg, w.stack)
  55. }
  56. var cause *wtError
  57. ok := As(w.cause, &cause)
  58. if ok {
  59. return fmt.Sprintf("[%s]%s: %s\n%s", w.code, w.msg, cause.Message(), w.stack)
  60. }
  61. return fmt.Sprintf("[%s]%s: %s\n%s", w.code, w.msg, w.cause.Error(), w.stack)
  62. }
  63. func (w *wtError) Stack() string {
  64. return w.stack
  65. }
  66. func (w *wtError) Error() string {
  67. return w.Message()
  68. }
  69. func (w *wtError) Cause() error {
  70. return w.cause
  71. }
  72. func (w *wtError) SetCode(code string) WTError {
  73. if w.code == UnknownError {
  74. return w.SetCodeForce(code)
  75. }
  76. return w
  77. }
  78. func (w *wtError) SetCodeForce(code string) WTError {
  79. w.code = code
  80. return w
  81. }
  82. func (w *wtError) SetCause(cause error) WTError {
  83. if w.cause == nil {
  84. return w.SetCauseForce(cause)
  85. }
  86. return w
  87. }
  88. func (w *wtError) SetCauseForce(cause error) WTError {
  89. w.cause = cause
  90. _ = w.SetCode(getErrorName(cause))
  91. var wtErr WTError
  92. if As(cause, &wtErr) {
  93. w.stack = wtErr.Stack()
  94. }
  95. return w
  96. }
  97. func (w *wtError) Warp(format string, a ...any) WTError {
  98. return Warp(w, format, a...)
  99. }