package response import ( "github.com/pkg/errors" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/rest/httpx" "google.golang.org/grpc/status" "live-service/common/nerr" "net/http" ) type Body struct { Code uint32 `json:"code"` Msg string `json:"message"` Data interface{} `json:"data,omitempty"` } func Error(code uint32, msg string) *Body { return &Body{ Code: code, Msg: msg, } } func Success(data interface{}) *Body { return &Body{ Code: http.StatusOK, Msg: "成功", Data: data, } } func Response(req *http.Request, w http.ResponseWriter, resp interface{}, err error) { if err == nil { r := Success(resp) httpx.WriteJson(w, http.StatusOK, r) return } // 错误返回 errCode := nerr.ServerCommonError errMsg := nerr.MapErrMsg(errCode) cause := errors.Cause(err) if e, ok := cause.(*nerr.Error); ok { // 自定义错误类型 errCode = e.Code errMsg = e.Msg } else { // grpc err if gStatus, ok := status.FromError(cause); ok { grpcCode := uint32(gStatus.Code()) if nerr.IsCodeErr(grpcCode) { // 区分自定义错误 系统底层、DB错误 (底层、DB错误不返回前端) errCode = grpcCode errMsg = gStatus.Message() } } } logx.WithContext(req.Context()).Errorf("[API-ERROR] %+v", err) httpx.WriteJson(w, http.StatusBadRequest, Error(errCode, errMsg)) }