Categories: GoFrame 教程

GoFrame 错误码特性-错误码扩展

当业务需要复杂的错误码定义时,我们推荐灵活使用错误码的​Detail​参数来扩展错误码功能。

我们来看个例子。

业务错误码

错误码定义

type BizCode struct {
 User User
 // ...
}

type User struct {
 Id   int
 Name string
 // ...
}

错误码使用

扩展错误码大多数场景下需要使用​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

因此上面我们的自定义扩展可以这么使用:

code := gcode.WithCode(gcode.CodeNotFound, BizCode{
 User: User{
  Id:   1,
  Name: "John",
 },
})
fmt.Println(code)

即在错误码中我们可以根据业务场景注入一些自定义的错误码扩展数据,以方便上层获取错误码后做进一步处理。

改写中间件

我们将上面自定义的错误码应用到请求返回中间件中,顶层业务逻辑也可以获取到错误码对应的详情再进一步做相关的业务处理。

func ResponseHandler(r *ghttp.Request) {
 r.Middleware.Next()
 // Theres 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​默认的日志中会自动打印​Detail​数据。

唐伯虎点蚊香

前端小白,想各位学习!

Share
Published by
唐伯虎点蚊香

Recent Posts

vue:页面注入js修改input值

一般会直接这样写: let z…

3 小时 ago

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago