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)
whereZ
is the zero value for typeT
Here, the "zero value" of "Error
" would be nil
.
You can use type assertions to do that:
if gormError, ok := err.(gorm.RecordNotFound); ok {
// handle RecordNotFound error
}
if myError, ok := err.(MyError); ok {
// handle MyError
}
When dealing with multiple error cases, it can be useful to use type switches for that:
switch actualError := err.(type) {
case gorm.RecordNotFound:
// handle RecordNotFound
case MyError:
// handle MyError
case nil:
// no error
}
The same way you would go about with any other interface. Use type assertion or a type switch:
switch err := err.(type) {
case MyValidationError:
fmt.Printf("validation error")
case MyOtherTypeOfError:
fmt.Printf("my other type of error")
default:
fmt.Printf("error of type %T", err)
}
Go Playground: http://play.golang.org/p/5-OQ3hxmZ5