feat: 内建 业务错误状态码+消息 缓存。

main v1.2.4
NoahLan 1 year ago
parent 29c064f702
commit eb07dba9bd

@ -1,6 +1,12 @@
package nstatus
import "git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
import (
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
)
/**
APIHTTP
*/
// NewApiErr 构建Api错误code为http状态码
func NewApiErr(code int, message string) error {

@ -1,10 +1,24 @@
package nstatus
import (
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/msg"
)
/**
500
*/
// NewBizErr 构建业务错误
func NewBizErr(code int, message string) error {
return NewResult(code, message, BizErr)
}
// NewBizErrWithCode 通过Code构建业务错误
func NewBizErrWithCode(c code.Code) error {
return NewBizErr(int(c), msg.Msg(c))
}
// NewBizErrNoMsg 构建业务错误,空错误消息
func NewBizErrNoMsg(code int) error {
return NewBizErr(code, "")

@ -2,8 +2,10 @@ package code
import "net/http"
type Code int
const (
StatusUnknown int = -1
StatusUnknown = -1
StatusOK = http.StatusOK
StatusFailed = 0
@ -11,7 +13,7 @@ const (
StatusUnauthorized = http.StatusUnauthorized
StatusForbidden = http.StatusForbidden
StatusNotFound = http.StatusNotFound
StatusRequestTimeout = http.StatusRequestTimeout
StatusRequestTimeoutCode = http.StatusRequestTimeout
StatusConflict = http.StatusConflict
StatusTooManyRequests = http.StatusTooManyRequests

@ -52,6 +52,10 @@ func IsGrpcErr(err error) bool {
return ok
}
/**
RPC
*/
func NewGrpcErr(code codes.Code, msg string) error {
return NewResult(int(code), msg, RpcErr)
}

@ -1,5 +1,12 @@
package msg
import (
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
"sync"
)
var codeMsgMap sync.Map
// message keys
const (
Success = "common.success"
@ -21,3 +28,17 @@ const (
AlreadyInit = "init.alreadyInit"
InitRunning = "init.initializeIsRunning"
)
// Add 添加消息
func Add(c code.Code, msg string) {
codeMsgMap.Store(c, msg)
}
// Msg 获取string消息
func Msg(c code.Code) string {
msg, ok := codeMsgMap.Load(c)
if ok {
return msg.(string)
}
return Failed
}

@ -28,13 +28,23 @@ func ResponseHandler(req *http.Request, w http.ResponseWriter, trans bool, resp
if trans {
result.Msg = i18n.Trans(req.Context(), result.Msg)
}
c := http.StatusInternalServerError
if result.Type == nstatus.ApiErr {
var c int
switch result.Type {
case nstatus.ApiErr:
// API错误按照Result内的code返回若code不是标准http错误则按照500返回
c = result.Code
if c > http.StatusNetworkAuthenticationRequired {
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)

Loading…
Cancel
Save