Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unclear behavior at specific error handling

Tags:

go

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")
    }
}
like image 713
hey Avatar asked Jul 30 '14 15:07

hey


1 Answers

What you can do:

  • compare err.Error(): if err != nil && err.Error() == "something"
  • use global variables for your errors

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.

like image 158
julienc Avatar answered Sep 19 '22 22:09

julienc