英文:
How check error codes with couchbase gocb?
问题
当处理[gocb](官方的Couchbase Go客户端)返回的错误时,我想要检查特定的状态码(例如StatusKeyNotFound
或StatusKeyExists
)。
像这样:
_, err := bucket.Get(key, entity)
if err != nil {
if err == gocb.ErrKeyNotFound {
...
}
}
可以这样做吗?
英文:
When handling errors returned by gocb (the official Couchbase Go Client) I would like to check for specific status codes (e.g. StatusKeyNotFound
or StatusKeyExists
).
Like so
_, err := bucket.Get(key, entity)
if err != nil {
if err == gocb.ErrKeyNotFound {
...
}
}
Can this be done?
答案1
得分: 4
这可以做到吗?
在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() {
// 处理 KeyNotFound
}
if se.KeyExists() {
// 处理 KeyExists
}
} else {
// 没有关于状态的信息
}
}
英文:
> Can this be done?
In gocbcore
, error.go we have the following definition:
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
}
Note that memdError
is unexported, so you can't use it in a type assertion.
So, take a different approach: define your own interface:
type MyErrorInterface interface {
KeyNotFound() bool
KeyExists() bool
}
And assert whatever error you get back from gocb
to your interface:
_, 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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论