errors.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package errors
  2. import "fmt"
  3. type withCode struct {
  4. err error
  5. code int
  6. cause error
  7. *stack
  8. }
  9. func WithCode(code int, format string, args ...interface{}) error {
  10. return &withCode{
  11. err: fmt.Errorf(format, args...),
  12. code: code,
  13. stack: callers(),
  14. }
  15. }
  16. func Wrap(err error, message string) error {
  17. if err == nil {
  18. return nil
  19. }
  20. if e, ok := err.(*withCode); ok {
  21. return &withCode{
  22. err: fmt.Errorf(message),
  23. code: e.code,
  24. cause: err,
  25. stack: callers(),
  26. }
  27. }
  28. return &withCode{
  29. err: fmt.Errorf(message),
  30. code: unknownCoder.Code(),
  31. cause: err,
  32. stack: callers(),
  33. }
  34. }
  35. func WrapC(err error, code int, format string, args ...interface{}) error {
  36. if err == nil {
  37. return nil
  38. }
  39. return &withCode{
  40. err: fmt.Errorf(format, args...),
  41. code: code,
  42. cause: err,
  43. stack: callers(),
  44. }
  45. }
  46. func (w *withCode) Error() string { return fmt.Sprintf("%v", w) }
  47. // Cause 返回根因
  48. func (w *withCode) Cause() error { return w.cause }
  49. // Unwrap 返回根因
  50. func (w *withCode) Unwrap() error { return w.cause }
  51. func Cause(err error) error {
  52. type causer interface {
  53. Cause() error
  54. }
  55. for err != nil {
  56. cause, ok := err.(causer)
  57. if !ok {
  58. break
  59. }
  60. if cause.Cause() == nil {
  61. break
  62. }
  63. err = cause.Cause()
  64. }
  65. return err
  66. }