可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
- 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 }
- 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.