[英]Error concrete type
I have a method CreateProduct(&Product) error
that returns a value implementing error
interface. 我有一个方法CreateProduct(&Product) error
,它返回一个实现error
接口的值。 It can be a gorm
database error or my own error type. 它可能是一个gorm
数据库错误或我自己的错误类型。
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
): 注意:即使在nil
上也可以进行类型断言(当err == nil
):
the result of the assertion is a pair of values with types
(T, bool)
. 断言的结果是一对带有类型(T, bool)
。
- If the assertion holds, the expression returns the pair
(x.(T), true)
; 如果断言成立,则表达式返回对(x.(T), true)
;- otherwise, the expression returns
(Z, false)
whereZ
is the zero value for typeT
否则,表达式返回(Z, false)
,其中Z
是类型T
的零值
Here, the "zero value" of " Error
" would be nil
. 这里,“ Error
”的“零值”将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 去游乐场: http : //play.golang.org/p/5-OQ3hxmZ5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.