如何使用Couchbase Gocb检查错误代码?

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?

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
    }
}