Checking for a Custom Error Type in Go
In Go, when defining custom error types, it's sometimes necessary to determine their specific type when handling errors. However, attempting to compare an error to a custom error type directly can lead to errors like "type model.ModelMissingError is not an expression".
To check for a custom error type, the Go blog post on errors recommends using the comma ok idiom:
serr, ok := err.(*model.ModelMissingError)
This idiom attempts to assert the error value err as a pointer to a specific type, in this case, model.ModelMissingError. If the assertion succeeds, serr will contain the underlying concrete value of the error, and ok will be true. Otherwise, serr will be nil, and ok will be false.
By using the comma ok idiom, you can safely check if an error is of a particular custom type and take appropriate action without triggering a panic:
if ok { // Handle the error as a ModelMissingError } else { // Handle the error as a different type }
This idiom is particularly useful when you have a common error interface that can represent multiple different errors, allowing you to distinguish between specific error types for tailored error handling.
The above is the detailed content of How Can I Safely Check for a Custom Error Type in Go?. For more information, please follow other related articles on the PHP Chinese website!