ZhangZhihui's Blog  

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
}

 

posted on   ZhangZhihuiAAA  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示