Go 1.13 introduces new features to the errors to simplify working with errors. Before Go 1.13, I checked my code for an error by this way:
if err == nil {
// ...
}
But Go's errors.Is()
helps me to do it properly:
It’s a sensible way to future-proof your code and prevent issues caused by you — or any packages that your code imports — wrapping errors in the future.
And that is ok for situations like this:
if errors.Is(err, sql.ErrNoRows) {
// ...
}
Does it mean that I have to change all my err == nil
statements to:
if errors.Is(err, nil) {
// ...
}
No, you don't. errors.Is checks the underlying error values. If some code returns sql.ErrNoRows and later decides to wrap that error, errors.Is(err, sql.ErrNoRows) continues working as before, but err == sql.ErrNoRows would evaluate to false.
A nil error value means there is no error, so there is nothing to wrap. There is no code you can write that changes what err != nil evaluates to while still returning no error. There is only one way to return no error: nil.
No. Not required. We use errors.Is() when an error is matched to the target, if its equal to the target it returns true. In your case err is nil which can't be used with the target.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With