Comparing Error Messages in Go
In Java, one can retrieve error messages using the GetMessage() method of the Exception class. In Go, however, error messages are accessed differently.
How to Compare Error Messages
To compare error messages in Go, follow these steps:
var errExample = errors.New("this is an example")
When an error occurs, return the package-level error variable instead of a custom string message:
return errExample
To check for the specific error, you can compare the returned error to the package-level error variable:
if err == errExample { // handle it }
Handling Errors from External Packages
If you need to compare errors from external packages, you can export the error variable:
var ErrExample = errors.New("this is an example")
Then, use the exported error variable in your code:
if err == somepackage.ErrExample { // handle it }
Avoid Using Error.Error()
Avoid comparing against the string returned from the Error() method of an error. This can make your code brittle as the error message can change without notice. Instead, use the recommended approach described above.
The above is the detailed content of How to Effectively Compare Error Messages in Go?. For more information, please follow other related articles on the PHP Chinese website!