errno.go 1.4 KB

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