You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/zero/statusz/handler.go

52 lines
1.5 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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)
}