-
Book Overview & Buying
-
Table Of Contents
Go Recipes for Developers
By :
In languages that support try-catch blocks, you usually catch errors based on their type. You can emulate the same functionality relying on errors.Is.
Implement the Is(error) bool method in your error type to define what type of equivalence you care about.
You may remember that the errors.Is(err,target) function first tests if err = target, and if that fails, it tests if err.Is(target), provided err implements the Is(error) bool method. So, you can use the Is(error) bool method to tune how to compare your custom error types. Without the Is(error) bool method, errors.Is will compare using ==, which will fail if the contents of two errors are different even if they are the same type. The following example allows you to check if the given error contains ErrSyntax somewhere in the error tree:
type ErrSyntax struct {
Line int
Col int
Err error
}
func ...