httpresult.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //@File httpresult.go
  2. //@Time 2022/04/26
  3. //@Author #Suyghur,
  4. package result
  5. import (
  6. "fmt"
  7. "github.com/pkg/errors"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. "github.com/zeromicro/go-zero/rest/httpx"
  10. "google.golang.org/grpc/status"
  11. "net/http"
  12. )
  13. func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
  14. if err == nil {
  15. // 成功返回
  16. result := Success(resp)
  17. httpx.WriteJson(w, http.StatusOK, result)
  18. } else {
  19. code := ServerCommonError
  20. msg := "some unknown error has occurred"
  21. cause := errors.Cause(err)
  22. if e, ok := cause.(*CodeError); ok {
  23. code = e.GetErrCode()
  24. msg = e.GetErrMsg()
  25. } else {
  26. if gStatus, ok := status.FromError(cause); ok {
  27. grpcCode := int32(gStatus.Code())
  28. if IsCodeErr(grpcCode) {
  29. code = grpcCode
  30. msg = gStatus.Message()
  31. } else {
  32. }
  33. }
  34. }
  35. logx.WithContext(r.Context()).Errorf("[API ERROR] : %+v", err)
  36. httpx.WriteJson(w, http.StatusBadRequest, Error(code, msg))
  37. }
  38. }
  39. func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
  40. logx.WithContext(r.Context()).Errorf("[API ERROR] : %+v", err)
  41. msg := fmt.Sprintf("%s ,%s", MapErrMsg(RequestParamError), err.Error())
  42. httpx.WriteJson(w, http.StatusBadRequest, Error(RequestParamError, msg))
  43. }