Comparing Error Messages in Go
In Go, errors are simply values that implement the error interface. This means that errors can be compared using the standard equality operators (== and !=). However, it is generally not recommended to compare errors by their string representation returned by the Error() method. This is because the string representation can change over time, which can make your code brittle.
A more reliable way to compare errors is to use a package-level variable that stores the expected error. This variable can be used to compare against the error returned by a function. For example:
package mypkg import ( "errors" ) // ErrExample is an example error. var ErrExample = errors.New("this is an example") // DoSomething returns an error if something goes wrong. func DoSomething() error { // ... // If something goes wrong, return the error. return ErrExample }
To compare against the error returned by DoSomething(), you can use the following code:
if err := DoSomething(); err != nil { // Handle the error. }
If the error returned by DoSomething() is equal to ErrExample, then the if statement will be executed.
You can also export the package-level variable if code outside the package needs to access the error. For example:
package mypkg import ( "errors" ) // ErrExample is an example error. var ErrExample = errors.New("this is an example") // Export the error. var ErrExample = ErrExample
To use the exported error, you can use the following code:
if err := somepackage.DoSomething(); err != nil { // Handle the error. }
If the error returned by somepackage.DoSomething() is equal to mypkg.ErrExample, then the if statement will be executed.
By using a package-level variable to compare errors, you can make your code more reliable and less brittle.
The above is the detailed content of How Can I Reliably Compare Errors in Go?. For more information, please follow other related articles on the PHP Chinese website!