Enriching your Go applications with custom error types enhances error handling, but manipulating these custom types can be challenging. Let's delve into the issue of checking for the type of a custom error.
Consider the following custom error type:
type ModelMissingError struct { msg string // description of error } func (e *ModelMissingError) Error() string { return e.msg }
Within a method, we can throw a custom error:
return Model{}, &ModelMissingError{"no model found for id"}
To determine if an error is a specific custom type, we need to check its type. However, the approach if err == model.ModelMissingError fails.
Go provides the comma ok idiom to check for type assertion:
serr, ok := err.(*model.ModelMissingError)
This statement asserts that the error variable err holds the model.ModelMissingError type and assigns the underlying value to the variable serr. If err does not hold the expected type, the statement will return nil for serr and false for ok.
By using the comma ok idiom, we can efficiently verify the type of a custom error and handle it accordingly.
The above is the detailed content of How Can I Check the Type of a Custom Error in Go?. For more information, please follow other related articles on the PHP Chinese website!