本章节仅介绍一些常用方法,完整的错误方法请参考接口文档: https://pkg.go.dev/github.com/gogf/gf/v2/errors/gerror

New/Newf

  • 说明:用于创建一个自定义错误信息的 error 对象,并包含堆栈信息。

  • 格式:

    1. // New creates and returns an error which is formatted from given text.
    2. New(text string) error
    3. // Newf returns an error that formats as the given format and args.
    4. Newf(format string, args ...interface{}) error

Wrap/Wrapf

  • 说明:用于包裹其他错误 error 对象,构造成多级的错误信息,包含堆栈信息。

  • 格式:

    1. // Wrap wraps error with text. It returns nil if given err is nil.
    2. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    3. func Wrap(err error, text string) error
    4. // Wrapf returns an error annotating err with a stack trace at the point Wrapf is called, and the format specifier.
    5. // It returns nil if given `err` is nil.
    6. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    7. func Wrapf(err error, format string, args ...interface{}) error

NewSkip/NewSkipf

  • 说明:用于创建一个自定义错误信息的 error 对象,并且忽略部分堆栈信息(按照当前调用方法位置往上忽略)。高级功能,一般开发者很少用得到。

  • 格式:

    1. // NewSkip creates and returns an error which is formatted from given text.
    2. // The parameter `skip` specifies the stack callers skipped amount.
    3. func NewSkip(skip int, text string) error
    4. // NewSkipf returns an error that formats as the given format and args.
    5. // The parameter `skip` specifies the stack callers skipped amount.
    6. func NewSkipf(skip int, format string, args ...interface{}) error

WrapSkip/WrapSkipf

  • 说明:类似于Warp/Wrapf方法,但会忽略部分堆栈信息。

  • 格式:

    1. // WrapSkip wraps error with text. It returns nil if given err is nil.
    2. // The parameter `skip` specifies the stack callers skipped amount.
    3. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    4. func WrapSkip(skip int, err error, text string) error
    5. // WrapSkipf wraps error with text that is formatted with given format and args. It returns nil if given err is nil.
    6. // The parameter `skip` specifies the stack callers skipped amount.
    7. // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    8. func WrapSkipf(skip int, err error, format string, args ...interface{}) error