Comparing errors
When you wrap an error with additional information, the new error value is not of the same type or value as the original error. For instance, os.Open
may return os.ErrNotExist
if the file is not found, and if you wrap this error with additional information, such as the file name, the caller of this function will need a way to get to the original error to handle it properly. This recipe shows how to deal with such wrapped error values.
How to do it...
Checking if there is an error or not is simple: check if an error value is nil
or not:
file, err := os.Open(fileName) if err!=nil { // File could not be opened }
Checking if an error is what you expect should be done using errors.Is
:
file, err := os.Open(fileName) if errors.Is(err,os.ErrNotExist) { // File does not exist }
How it works...
errors.Is(err,target error)
compares if err
is equal to target
by doing the following:
- It checks if
err==target
. - If that fails,...