Extracting a specific error from the error tree
How to do it...
Use the errors.As
function to descend an error tree, find a particular error, and extract it.
How it works...
Similar to the errors.Is
function, errors.As(err error, target any) bool
descends the error tree of err
until an error that is assignable to target
is found. That is done by the following:
- It checks if the value pointed to by
target
is assignable to the value pointed to byerr
. - If that fails, it checks if
err
has anAs(error) bool
method by callingerr.As(target)
. If it returnstrue
, then an error is found. - If not, it checks if
err
has anUnwrap() error
method anderr.Unwrap()
is notnil
, descending the tree. - Otherwise, it checks if
err
has anUnwrap() []error
method, and if it returns a non-empty slice, it descends the tree for each of those until a match is found.
In other words, errors.As
copies the error that can be assigned to target
into target
.
The following example...