GoFrame 錯(cuò)誤碼特性-錯(cuò)誤碼擴(kuò)展

2022-03-30 10:24 更新

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

我們來(lái)看個(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)一步處理。

改寫(xiě)中間件

我們將上面自定義的錯(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ù)。


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)