Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

errors.Is in Go 1.13

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) {
    // ...
}
like image 672
Ali Mamedov Avatar asked Oct 25 '19 07:10

Ali Mamedov


2 Answers

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.

like image 84
Peter Avatar answered Nov 07 '22 00:11

Peter


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.

like image 38
Kshitij Gugale Avatar answered Nov 07 '22 02:11

Kshitij Gugale