Problem: You want to provide additional information and context to an error you receive before returning it as another error.
Solution: Wrap the error you receive with another error you create before returning it.
There are a couple of ways to wrap errors. The easiest is to use fmt.Errorf again and provide an error as part of the parameter:
err1 := errors.New("Oops something happened.") err2 := fmt.Errorf("An error was encountered - %w", err1)
The %w verb allows you to place an error within the format string. In the example, err2 wraps err1 . But how do you extract err1 out of err2 ?
The errors package has an Unwrap function that does precisely this:
err := errors.Unwrap(err2)
This will give you back err1 .
Another way of wrapping an error with an error is to create a customized error struct like this:
type ConnectionError struct { Host string Port int Err error } func (err *ConnectionError) Error() string { return fmt.Sprintf("Error connecting to %s at port %d", err.Host, err.Port) }
Remember, to make it an error, the struct should have an Error method. To allow the struct to be unwrapped, you need to implement an Unwrap function:
func (err *ConnectionError) Unwrap() error { return err.Err }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律