Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Alexander Kleinhans Avatar asked Jan 10 '17 02:01

Alexander Kleinhans


2 Answers

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.

like image 184
Bayta Darell Avatar answered Sep 27 '22 21:09

Bayta Darell


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.

like image 29
amku91 Avatar answered Sep 27 '22 20:09

amku91