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?
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.
we can also compare errors like that:
_
var errExample = errors.New("ERROR_CODE")
then you can directly check error like this
if err.Error() == "ERROR_CODE" {
//Do something error caught
}
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.
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