百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
F

failure

> 编程语言
开源

failure 是一个用于处理应用程序错误的实用程序包。

368 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

failure 是一个用于处理应用程序错误的实用程序包。

failure

Package failure is an error handling library for Go. It allows you to create, wrap, and handle errors with additional context and features.

Features

  • Create errors with error codes to easily classify and handle errors.
  • Wrap errors with additional context such as function parameters and key-value data.
  • Automatically capture call stack information for debugging.
  • Flexible error formatting for both developers and end users.
  • Utility functions to extract error codes, messages, and other metadata from errors.

Installation

To install failure, use the following command:

go get github.com/morikuni/failure/v2

Usage Examples

First, define your application's error codes:

go
type ErrorCode string

const (
    ErrNotFound ErrorCode = "NotFound"
    ErrInvalidArgument ErrorCode = "InvalidArgument"
)

Use failure.New to create a new error with an error code:

go
err := failure.New(ErrNotFound, failure.Message("Resource not found"))

Use failure.Wrap to wrap an existing error with additional context:

go
if err != nil {
    return failure.Wrap(err, failure.Context{"parameter": "value"})
}

Use failure.Is to check for a specific error code and handle the error:

go
if failure.Is(err, ErrNotFound) {
    // Handle ErrNotFound error
}

Use utility functions to extract metadata from the error:

go
code := failure.CodeOf(err)
message := failure.MessageOf(err)
callStack := failure.CallStackOf(err)

Example error outputs:

go
err := failure.New(ErrInvalidArgument, failure.Message("Invalid argument"), failure.Context{"userId": "123"})
fmt.Println(err) 
// Output: GetUser[InvalidArgument](Invalid argument, {userId=123})

fmt.Printf("%+v\n", err)
// Output:
// [main.GetUser] /path/to/file.go:123
//     InvalidArgument
//     Invalid argument
//     {userId=123}
// [CallStack]
//     [main.GetUser] /path/to/file.go:123
//     [main.main] /path/to/main.go:456

For more detailed usage and examples, refer to the Go Reference.

Full Example of Usage

…

Migration from v1 to v2

See docs/v1-to-v2.md for migration guide.

Contributing

Contributions are welcome! Feel free to send issues or pull requests.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Goerrorerror-handlinggogolang

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言