---
title: "错误处理-常用方法"
url: "https://goframe.org/docs/core/gerror-funcs"
markdown_url: "https://goframe.org/docs/core/gerror-funcs.md"
locale: "zh-Hans"
version: "2.10.x(Latest)"
section: "核心组件"
category: "核心组件 / 错误处理"
published: "2024-10-21"
updated: "2026-02-11"
description: "深入介绍`GoFrame`框架`gerror`组件的常用方法，包括错误创建方法`New/Newf`（创建带堆栈信息的错误）、错误包装方法`Wrap/Wrapf`（构造多级错误链）、以及高级方法`NewSkip/NewSkipf`和`WrapSkip/WrapSkipf`（忽略部分堆栈信息），帮助开发者有效管理和调试错误。"
keywords: ["GoFrame", "GoFrame框架", "错误处理", "错误创建", "New", "Wrap", "NewSkip", "错误码", "gerror", "堆栈信息"]
---

# 错误处理-常用方法

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

## `New/Newf`

- 说明：用于创建一个自定义错误信息的`error`对象，并包含堆栈信息。
- 格式：

    ```go
    // New creates and returns an error which is formatted from given text.
    New(text string) error

    // Newf returns an error that formats as the given format and args.
    Newf(format string, args ...interface{}) error
    ```

## `Wrap/Wrapf`

- 说明：用于包裹其他错误 `error` 对象，构造成多级的错误信息，包含堆栈信息。
- 格式：

    ```go
    // Wrap wraps error with text. It returns nil if given err is nil.
    // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    func Wrap(err error, text string) error

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

## `NewSkip/NewSkipf`

- 说明：用于创建一个自定义错误信息的 `error` 对象，并且忽略部分堆栈信息（按照当前调用方法位置往上忽略）。高级功能，一般开发者很少用得到。
- 格式：

    ```go
    // NewSkip creates and returns an error which is formatted from given text.
    // The parameter `skip` specifies the stack callers skipped amount.
    func NewSkip(skip int, text string) error

    // NewSkipf returns an error that formats as the given format and args.
    // The parameter `skip` specifies the stack callers skipped amount.
    func NewSkipf(skip int, format string, args ...interface{}) error
    ```

## `WrapSkip/WrapSkipf`

- 说明：类似于`Warp/Wrapf`方法，但会忽略部分堆栈信息。
- 格式：

    ```go
    // WrapSkip wraps error with text. It returns nil if given err is nil.
    // The parameter `skip` specifies the stack callers skipped amount.
    // Note that it does not lose the error code of wrapped error, as it inherits the error code from it.
    func WrapSkip(skip int, err error, text string) error 

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