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 2023-09-29 10:24  ZhangZhihuiAAA  阅读(7)  评论(0编辑  收藏  举报