package statusz import ( "git.noahlan.cn/noahlan/ntool-biz/core/i18n" "git.noahlan.cn/noahlan/ntool-biz/core/nstatus" "git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg" "github.com/zeromicro/go-zero/rest/httpx" "net/http" ) // ResponseHandler API执行结果处理,统一返回值类型与结构 func ResponseHandler(req *http.Request, w http.ResponseWriter, trans bool, resp any, err error) { if err == nil { r := nstatus.NewResultWithData(http.StatusOK, msg.Success, nstatus.CommonResult, resp) if trans { r.Msg = i18n.Trans(req.Context(), r.Msg) } httpx.WriteJson(w, http.StatusOK, r) return } result := nstatus.ConvertErr(err) if result == nil { // 不可能发生此情况,这里处理是以防万一 result = nstatus.NewResult(http.StatusOK, msg.Success, nstatus.CommonResult) } result.Data = resp if trans { result.Msg = i18n.Trans(req.Context(), result.Msg) } var c int switch result.Type { case nstatus.ApiErr: // API错误,按照Result内的code返回,若code不是标准http错误,则按照500返回 c = result.Code if c > http.StatusNetworkAuthenticationRequired || c < http.StatusContinue { c = http.StatusInternalServerError } case nstatus.BizErr: // 业务代码类型错误,统一状态码为500 c = http.StatusInternalServerError case nstatus.RpcErr: // RPC错误,统一状态码为500 c = http.StatusInternalServerError default: c = http.StatusInternalServerError } // 其它错误统一按照500返回 httpx.WriteJson(w, c, result) }