errors.Is
The function that reports whether an error, or any error wrapped inside it, is a particular target error.
In more detail
Use errors.Is(err, os.ErrNotExist) instead of comparing message text, which breaks as soon as someone rewords a message. errors.As does the same search but looks for an error of a given type and extracts it.
Example
if errors.Is(err, ErrMissing) {
fmt.Println("use defaults")
}Related terms
- error wrapping — Adding context to an error while keeping the original error inside it, so the message explains what failed and code can still test the cause.
- sentinel error — A specific error value published in a package-level variable, such as io.EOF or os.ErrNotExist, that callers can test for with errors.Is.
- os.ErrNotExist — The sentinel error Go file functions return, wrapped, when a file or folder does not exist.
Taught in
- Wrapping Errors and errors.Is — Concurrent Systems Programming with Go
- Files and the os Package — Concurrent Systems Programming with Go