Compare error message in golang

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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?

回答1:

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.



回答2:

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.



转载请标明出处:Compare error message in golang
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!