如何使用 couchbase gocb 检查错误代码?

How check error codes with couchbase gocb?

当处理 gocb(官方 Couchbase Go 客户端)返回的错误时,我想检查特定的状态代码(例如 StatusKeyNotFoundStatusKeyExists)。

像这样

_, err := bucket.Get(key, entity)
if err != nil {
    if err == gocb.ErrKeyNotFound {
        ...
    }
}

这可以做到吗?

Can this be done?

gocbcore 中,error.go 我们有 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
}

请注意,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
    }
}