response.go 950 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package response
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "gogs.tyduyong.com/duyong/dy-pkg/errors"
  5. "gogs.tyduyong.com/duyong/dy-pkg/logs"
  6. "net/http"
  7. )
  8. type ErrResponse struct {
  9. // Code defines the business error code.
  10. Code int `json:"code"`
  11. // Message contains the detail of this message.
  12. // This message is suitable to be exposed to external
  13. Message string `json:"message"`
  14. // Reference returns the reference document which maybe useful to solve this error.
  15. Reference string `json:"reference,omitempty"`
  16. }
  17. // WriteResponse 如果错误是来自我们自己的错误包。返回时会解析并打印错误日志
  18. func WriteResponse(c *gin.Context, err error, data interface{}) {
  19. if err != nil {
  20. logs.Errorf("%#+v", err)
  21. coder := errors.ParseCoder(err)
  22. c.JSON(coder.HTTPStatus(), ErrResponse{
  23. Code: coder.Code(),
  24. Message: coder.String(),
  25. Reference: coder.Reference(),
  26. })
  27. return
  28. }
  29. c.JSON(http.StatusOK, data)
  30. }