---
title: "错误处理-错误码接口"
url: "https://goframe.org/docs/core/gerror-code-interface"
markdown_url: "https://goframe.org/docs/core/gerror-code-interface.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()`返回错误详细信息。框架提供默认实现，开发者可通过`New`方法创建错误码，也可自定义实现`Code`接口满足复杂业务需求。"
keywords: ["GoFrame", "GoFrame框架", "gcode", "错误处理", "错误码接口", "接口定义", "高扩展性", "错误码组件", "自定义错误码", "接口化设计"]
---

# 错误处理-错误码接口

## 基本介绍

我们前面讲到的主要是`gerror`组件的使用，该组件主要用于错误管理。在后续章节中，我们主要讲解`gcode`组件的使用，该组件主要用于扩展`gerror`组件的能力，提供错误码的特性。`gcode`错误码组件使用了接口化设计，以提供高扩展性。

**使用方式**：

```go
import "github.com/gogf/gf/v2/errors/gcode"
```

**接口文档**：

[https://pkg.go.dev/github.com/gogf/gf/v2/errors/gcode](https://pkg.go.dev/github.com/gogf/gf/v2/errors/gcode)

## 接口定义

```go
// Code is universal error code interface definition.
type Code interface {
    // Code returns the integer number of current error code.
    Code() int

    // Message returns the brief message for current error code.
    Message() string

    // Detail returns the detailed information of current error code,
    // which is mainly designed as an extension field for error code.
    Detail() interface{}
}
```

## 默认实现

框架提供了默认实现 `gcode.Code` 的结构体，开发者可以直接`gcode`组件的`New/WithCode`方法创建错误码：

- 格式：

    ```go
    // New creates and returns an error code.
    // Note that it returns an interface object of Code.
    func New(code int, message string, detail interface{}) Code
    ```

- 示例：

    ```go
    func ExampleNew() {
        c := gcode.New(1, "custom error", "detailed description")
        fmt.Println(c.Code())
        fmt.Println(c.Message())
        fmt.Println(c.Detail())

        // Output:
        // 1
        // custom error
        // detailed description
    }
    ```

如果开发者觉得框架默认实现 `gcode.Code` 的结构体不满足需求，可以自行定义，只需实现 `gcode.Code` 即可。
