Comparing Error Messages in Go
In Java, you can use GetMessage() to retrieve the error message from an Exception. However, in Go, there is no equivalent method defined for the error type. Instead, custom error handling techniques must be employed.
Custom Error Handling
One approach is to define a package-level variable to represent the specific error message you want to check for. For instance:
var errExample = errors.New("this is an example")
When returning errors, you can use this variable instead of a generic error string:
if err := some_package.DoSomething(); err != nil { if err == errExample { // handle it however. } }
Exporting the Error Variable
If code outside the package needs to access the error, you can export the variable using a capital letter:
var ErrExample = errors.New("this is an example")
This allows you to compare the error against the exported variable:
if err == somepackage.ErrExample { // handle it }
Examples
Pitfall: Avoid String Comparison
Resist the temptation to compare against the string returned by the error's Error() method. This can result in brittle code. For instance:
if err.Error() == "this is an example" { // this is not recommended }
Instead, use the custom error handling approach outlined above.
The above is the detailed content of How Do I Effectively Compare and Handle Errors in Go, Unlike Java\'s GetMessage()?. For more information, please follow other related articles on the PHP Chinese website!