在处理由戈克布 (正式的Couchbase Go客户端)返回的错误时,我想检查特定的状态代码(例如,StatusKeyNotFound或StatusKeyExists)。
就像这样
_, err := bucket.Get(key, entity)
if err != nil {
if err == gocb.ErrKeyNotFound {
...
}
}这能办到吗?
发布于 2015-06-19 12:03:04
这能办到吗?
在gocbcore,error.go,我们有以下定义
type memdError struct {
code StatusCode
}
// ...
func (e memdError) KeyNotFound() bool {
return e.code == StatusKeyNotFound
}
func (e memdError) KeyExists() bool {
return e.code == StatusKeyExists
}
func (e memdError) Temporary() bool {
return e.code == StatusOutOfMemory || e.code == StatusTmpFail
}
func (e memdError) AuthError() bool {
return e.code == StatusAuthError
}
func (e memdError) ValueTooBig() bool {
return e.code == StatusTooBig
}
func (e memdError) NotStored() bool {
return e.code == StatusNotStored
}
func (e memdError) BadDelta() bool {
return e.code == StatusBadDelta
}请注意,memdError是未导出的,因此不能在类型断言中使用它。
因此,采取一种不同的方法:定义自己的接口:
type MyErrorInterface interface {
KeyNotFound() bool
KeyExists() bool
}并断言从gocb返回到界面的任何错误:
_, err := bucket.Get(key, entity)
if err != nil {
if se, ok = err.(MyErrorInterface); ok {
if se.KeyNotFound() {
// handle KeyNotFound
}
if se.KeyExists() {
// handle KeyExists
}
} else {
// no information about states
}
}https://stackoverflow.com/questions/30931951
复制相似问题