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:

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

Interface Documentation:

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

Interface Definition

  1. // Code is universal error code interface definition.
  2. type Code interface {
  3. // Code returns the integer number of current error code.
  4. Code() int
  5. // Message returns the brief message for current error code.
  6. Message() string
  7. // Detail returns the detailed information of current error code,
  8. // which is mainly designed as an extension field for error code.
  9. Detail() interface{}
  10. }

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:

    1. // New creates and returns an error code.
    2. // Note that it returns an interface object of Code.
    3. func New(code int, message string, detail interface{}) Code
  • Example:

    1. func ExampleNew() {
    2. c := gcode.New(1, "custom error", "detailed description")
    3. fmt.Println(c.Code())
    4. fmt.Println(c.Message())
    5. fmt.Println(c.Detail())
    6. // Output:
    7. // 1
    8. // custom error
    9. // detailed description
    10. }

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.