errno.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package errno
  2. import (
  3. "encoding/json"
  4. "git.bvbej.com/bvbej/base-golang/pkg/errors"
  5. )
  6. var _ Error = (*err)(nil)
  7. type Error interface {
  8. // i 为了避免被其他包实现
  9. i()
  10. // WithErr 设置错误信息
  11. WithErr(err error) Error
  12. // GetBusinessCode 获取 Business Code
  13. GetBusinessCode() int
  14. // GetHttpCode 获取 HTTP Code
  15. GetHttpCode() int
  16. // GetMsg 获取 Msg
  17. GetMsg() string
  18. // GetErr 获取错误信息
  19. GetErr() error
  20. // ToString 返回 JSON 格式的错误详情
  21. ToString() string
  22. }
  23. type err struct {
  24. HttpCode int // HTTP Code
  25. BusinessCode int // Business Code
  26. Message string // 描述信息
  27. Err error // 错误信息
  28. }
  29. func NewError(httpCode, businessCode int, msg string) Error {
  30. return &err{
  31. HttpCode: httpCode,
  32. BusinessCode: businessCode,
  33. Message: msg,
  34. }
  35. }
  36. func (e *err) i() {}
  37. func (e *err) WithErr(err error) Error {
  38. e.Err = errors.WithStack(err)
  39. return e
  40. }
  41. func (e *err) GetHttpCode() int {
  42. return e.HttpCode
  43. }
  44. func (e *err) GetBusinessCode() int {
  45. return e.BusinessCode
  46. }
  47. func (e *err) GetMsg() string {
  48. return e.Message
  49. }
  50. func (e *err) GetErr() error {
  51. return e.Err
  52. }
  53. // ToString 返回 JSON 格式的错误详情
  54. func (e *err) ToString() string {
  55. err := &struct {
  56. HttpCode int `json:"http_code"`
  57. BusinessCode int `json:"business_code"`
  58. Message string `json:"message"`
  59. }{
  60. HttpCode: e.HttpCode,
  61. BusinessCode: e.BusinessCode,
  62. Message: e.Message,
  63. }
  64. raw, _ := json.Marshal(err)
  65. return string(raw)
  66. }