Skip to main content
Version: 2.8.x(Latest)

Introduction

Previously, we discussed the usage of the gerror component, which is mainly used for error management. In subsequent chapters, we will primarily explain the use of the gcode component, which is mainly used to extend the capabilities of the gerror component by providing error code features. The gcode error code component uses an interface design to offer high scalability.

Usage:

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

Interface Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/errors/gcode

Interface Definition

// 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{}
}

Default Implementation

The framework provides a default implementation structure for gcode.Code. Developers can directly use the gcode component's New/WithCode methods to create error codes:

  • Format:

    // 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
  • Example:

    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
    }

If developers find that the framework's default implementation structure for gcode.Code does not meet their needs, they can define their own implementation as long as they implement gcode.Code.