Alexander Kleinhans
Alexander Kleinhans

Reputation: 6248

Compare error message in golang

Let's say I create a new error in golang like so

err := errors.New("SOME_COMMON_ERROR_CODE")

In java, I'm used to being able to get Exception with GetMessage() messages. How would I compare that error if returned?

if some_err := some_package.DoSomething(); some_err != nil {
    if some_err.GetMessage() == "SOME_COMMON_ERROR_CODE" {
        // handle it however.
    }
}

How is this done in golang?

Upvotes: 10

Views: 13263

Answers (2)

amku91
amku91

Reputation: 1038

we can also compare errors like that:

  1. If you creating error like this [Error Code Based]

_

var errExample = errors.New("ERROR_CODE")

then you can directly check error like this

if err.Error() == "ERROR_CODE" {
//Do something error caught
}
  1. If you creating error like this [Error Code Based]

package mypackage

var NoMoreData = errors.New("No more data")

Now you can check anywhere like this

if err != mypackage.NoMoreData{
//Do something error caught
}

If you want to compare two errors at a time then you can do like this:

err1 := errors.New("Error Caught")
err2 := errors.New("Error Caught")

fmt.Println(err1 == err2) // false | Never do like this

fmt.Println(err1.Error() == err2.Error()) // true | Do like this

That's All.

Upvotes: 10

Thundercat
Thundercat

Reputation: 120941

Declare a package level variable with the error:

var errExample = errors.New("this is an example")

Use this value when returning errors. Compare against this value to check for the specific error:

if err == errExample {
    // handle it
}

Export the variable if code outside the package needs to access the error:

var ErrExample = errors.New("this is an example")

Use it like this:

if err == somepackage.ErrExample {
    // handle it
}

Here are some examples.

Avoid comparing against the string returned from the error's Error() method. It can make your code brittle.

Upvotes: 13

Related Questions