当业务需要更复杂的错误码定义时,我们可以自定义实现业务自己的错误码,只需要实现gcode.Code
相关的接口即可。
我们来看个例子。
自定义错误码
定义结构体并实现gcode.code
接口定义的方法
type BizCode struct {
code int
message string
detail BizCodeDetail
}
type BizCodeDetail struct {
Code string
HttpCode int
}
func (c BizCode) BizDetail() BizCodeDetail {
return c.detail
}
func (c BizCode) Code() int {
return c.code
}
func (c BizCode) Message() string {
return c.message
}
func (c BizCode) Detail() interface{} {
return c.detail
}
func New(httpCode int, code string, message string) gcode.Code {
return BizCode{
code: 0,
message: message,
detail: BizCodeDetail{
Code: code,
HttpCode: httpCode,
},
}
}
定义业务错误码
var (
CodeNil = New(200, "OK", "")
CodeNotFound = New(404, "Not Found", "Resource does not exist")
CodeInternal = New(500, "Internal Error", "An error occurred internally")
// ...
)
使用到中间件
func ResponseHandler(r *ghttp.Request) {
r.Middleware.Next()
// There's custom buffer content, it then exits current handler.
if r.Response.BufferLength() > 0 {
return
}
res, err := r.GetHandlerResponse()
code := gerror.Code(err)
if code == gcode.CodeNil && err != nil {
code = CodeInternal
} else {
code = CodeNil
}
if bizCode, ok := code.(BizCode); ok {
r.Response.WriteStatus(bizCode.BizDetail().HttpCode)
}
_ = r.Response.WriteJson(g.Map{
`code`: gcode.CodeOK.Code(),
`message`: gcode.CodeOK.Message(),
`data`: res,
})
}