I'm trying to handle specific errors but I'm surprised about the behavior.
Examples:
If I use
if err == errors.New("something"){}`
it returns true
, even if err
is nil
.
If I use
if err.String() == "something"`
it panics when err
is nil
.
I really expected
err == errors.New("something")`
to work and I'm not sure why it returns true
.
Some more code:
Here is some code to clarify the question (Play):
package main
import "fmt"
import "errors"
func main() {
e := errors.New("error")
//I'm expecting this to return true
if e == errors.New("error") {
fmt.Println("Hello, playground")
}
}
What you can do:
err.Error()
: if err != nil && err.Error() == "something"
Here is an example for the second solution:
package my_package
var ErrSmth = errors.New("something")
func f() error {
return ErrSmth
}
package main
import "my_package"
func main() {
err := f()
if err == my_package.ErrSmth {
// Do something
}
}
The second solution is the way specific errors are handled with the io
package.
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