I have a method CreateProduct(&Product) error that returns a value implementing error interface. It can be a gorm database error or my own error type.
Having the returned value, how can I know which type is the error?
err = api.ProductManager.CreateProduct(product)
if err != nil {
// TODO: how to distinguish that it is a validation error?
response.WriteHeader(422)
response.WriteJson(err)
return
}
You can do a type assertion, and act if the error returned is from the expected type:
if nerr, ok := err.(yourError); ok {
// do something
}
You can also do a type switch for multiple test
switch t := err.(type) {
case yourError:
// t is a yourError
case otherError :
// err is an otherError
case nil:
// err was nil
default:
// t is some other type
}
Note: a type assertion is possible even on nil (when err == nil):
the result of the assertion is a pair of values with types
(T, bool).
- If the assertion holds, the expression returns the pair
(x.(T), true);- otherwise, the expression returns
(Z, false)whereZis the zero value for typeT
Here, the "zero value" of "Error" would be nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With