新聞中心
當(dāng)業(yè)務(wù)需要復(fù)雜的錯(cuò)誤碼定義時(shí),我們推薦靈活使用錯(cuò)誤碼的?Detail?參數(shù)來擴(kuò)展錯(cuò)誤碼功能。

創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都做網(wǎng)站、成都網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元長(zhǎng)壽做網(wǎng)站,已為上家服務(wù),為長(zhǎng)壽各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
我們來看個(gè)例子。
業(yè)務(wù)錯(cuò)誤碼
錯(cuò)誤碼定義
type BizCode struct {
User User
// ...
}
type User struct {
Id int
Name string
// ...
}錯(cuò)誤碼使用
擴(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ù)。
新聞名稱:創(chuàng)新互聯(lián)GoFrame教程:GoFrame 錯(cuò)誤碼特性-錯(cuò)誤碼擴(kuò)展
網(wǎng)頁地址:http://m.fisionsoft.com.cn/article/cdjcphe.html


咨詢
建站咨詢
