Errors, Type Assertion, mgo.Bulk

polaris · 2017-09-16 12:00:04 · 899 次点击    
这是一个分享于 2017-09-16 12:00:04 的资源,其中的信息可能已经有所发展或是发生改变。

While working with the MongoDB driver, mgo, it occurred to me that the topic of errors with type assertion can be somewhat unclear. Consider the following code which performs a bulk insert of documents into the database.

... 
var bulkErrs []mgo.BulkErrorCase
var err error
_, err = bulk.Run()
if err != nil {
    bulkErrs = err.(*mgo.BulkError).Cases()
    for _, case := range bulkErrs {
        log.Println(case.Index, case.Err)
    }
}

In this example the returned err contains information on all the errors that occurred during the bulk.Run() process.

The type of variable "err" is "error", but in this example type assertion is used so features of the underlying actual concrete type can be used.

Since the built-in type "error" is an interface type, error values can be any concrete type that has a method with the following signature: Error() string.


评论:

natefinch:

don't do this:

bulkErrs = err.(*mgo.BulkError).Cases()

The type cast can fail, in which case, this panics

What you want to do is this:

bulkErr, ok = err.(*mgo.BulkError)
if !ok {  
    // not a bulk error
}
for _, case := range bulkErr.Cases() {
    // 
}
kidovate:

This isn't so bad, you can do a type switch on your errors to get a catch type syntax.

robe_and_wizard_hat:

Yes, it's unfortunate. Perhaps bulk.Run() should have declared to return an *mgo.BulkError instead.

euank:

Absolutely not! This is one of Go's big gotchas; returning a struct when a caller might expect an interface makes nil comparisons iffy. Always return interfaces when your caller might ever interpret it as such.

Here's an example of how this can shoot you in the foot: https://play.golang.org/p/RBkfTmRQST

Note how 'case 2' can be turned into 'case 3' by some simple refactoring, so even if you start with correct code, it's basically a timebomb to define functions that return like that.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

899 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传