W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
當(dāng)業(yè)務(wù)需要復(fù)雜的錯(cuò)誤碼定義時(shí),我們推薦靈活使用錯(cuò)誤碼的?Detail
?參數(shù)來(lái)擴(kuò)展錯(cuò)誤碼功能。
我們來(lái)看個(gè)例子。
type BizCode struct {
User User
// ...
}
type User struct {
Id int
Name string
// ...
}
擴(kuò)展錯(cuò)誤碼大多數(shù)場(chǎng)景下需要使用?WithCode
?方法:
// WithCode creates and returns a new error code based on given Code.
// The code and message is from given `code`, but the detail if from given `detail`.
func WithCode(code Code, detail interface{}) Code
因此上面我們的自定義擴(kuò)展可以這么使用:
code := gcode.WithCode(gcode.CodeNotFound, BizCode{
User: User{
Id: 1,
Name: "John",
},
})
fmt.Println(code)
即在錯(cuò)誤碼中我們可以根據(jù)業(yè)務(wù)場(chǎng)景注入一些自定義的錯(cuò)誤碼擴(kuò)展數(shù)據(jù),以方便上層獲取錯(cuò)誤碼后做進(jìn)一步處理。
我們將上面自定義的錯(cuò)誤碼應(yīng)用到請(qǐng)求返回中間件中,頂層業(yè)務(wù)邏輯也可以獲取到錯(cuò)誤碼對(duì)應(yīng)的詳情再進(jìn)一步做相關(guān)的業(yè)務(wù)處理。
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 = gcode.CodeInternalError
}
if detail, ok := code.Detail().(BizCode); ok {
g.Log().Errorf(r.Context(), `error caused by user "%+v"`, detail.User)
}
_ = r.Response.WriteJson(ghttp.DefaultHandlerResponse{
Code: gcode.CodeOK.Code(),
Message: gcode.CodeOK.Message(),
Data: res,
})
}
在框架?Server
?默認(rèn)的日志中會(huì)自動(dòng)打印?Detail
?數(shù)據(jù)。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: