dongshengli6384
dongshengli6384
2015-06-19 07:02
浏览 73
已采纳

如何使用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?

图片转代码服务由CSDN问答提供 功能建议

处理 gocb (Couchbase Go官方客户端),我想检查特定的状态代码(例如 StatusKeyNotFound StatusKeyExists )。

像这样

  _,err:= bucket.Get(键,实体)
if err!= nil {
如果err == gocb  .ErrKeyNotFound {
 ... 
} 
} 
   
 
 

可以做到吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhe5092
    douhe5092 2015-06-19 12:03
    已采纳

    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
        }
    }
    
    点赞 评论

相关推荐