1
0

errors.go 2.1 KB

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