Wrapping errors to add contextual information
Using the standard library errors
package, you can wrap an error with another error that contains additional contextual information. This package also provides facilities and conventions that will let you check if an error tree contains a particular error or extract a particular error from an error tree.
How to do it...
Add contextual information to an error using fmt.Errorf
. In the following example, the returned error will contain the error returned from os.Open
, and it will also include the file name:
file, err := os.Open(fileName) if err!=nil { return fmt.Errorf("%w: While opening %s",err,fileName) }
Note the use of %w
verb in fmt.Errorf
above. The %w verb is used to create an error wrapping the one given as its argument. If we used %v or %s, the returned error would contain the text of the original error, but it would not wrap it.