---
title: "错误处理-错误码实现"
url: "https://goframe.org/docs/core/gerror-code-custom"
markdown_url: "https://goframe.org/docs/core/gerror-code-custom.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "核心组件"
category: "核心组件 / 错误处理 / 错误处理-错误码特性"
published: "2024-10-21"
updated: "2026-02-11"
description: "详细讲解`GoFrame`框架中如何自定义实现复杂的业务错误码。通过实现`gcode.Code`接口，定义包含`code`、`message`和自定义`detail`的错误码结构体`BizCode`。示例展示了如何定义业务错误码（如`CodeNotFound`、`CodeInternal`）并在中间件中使用，将HTTP状态码和自定义错误信息结合返回给客户端，实现灵活的错误处理机制。"
keywords: ["GoFrame", "GoFrame框架", "错误处理", "错误码", "自定义错误码", "gcode", "业务错误码", "HttpCode", "中间件", "代码示例"]
---

# 错误处理-错误码实现

当业务需要更复杂的错误码定义时，我们可以自定义实现业务的错误码，只需要实现`gcode.Code`相关的接口即可。

我们来看个例子。

## 自定义错误码

定义基础的业务错误码结构体，实现`gcode.Code`接口。

```go
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,
        },
    }
}
```

定义业务错误码

```go
var (
    CodeNil      = New(200, "OK", "")
    CodeNotFound = New(404, "Not Found", "Resource does not exist")
    CodeInternal = New(500, "Internal Error", "An error occurred internally")
    // ...
)
```

## 使用到中间件

```go
func ResponseHandler(r *ghttp.Request) {
    r.Middleware.Next()
    // There's custom buffer content, it then exits current handler.
    if r.Response.BufferLength() > 0 {
        return
    }
    var (
        err  = r.GetError()
        res  = 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,
    })
}
```
