<p>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. </p>
<pre><code>...
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)
}
}
</code></pre>
<p>In this example the returned err contains information on all the errors that occurred during the bulk.Run() process. </p>
<p>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. </p>
<p>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. </p>
<hr/>**评论:**<br/><br/>natefinch: <pre><p>don't do this:</p>
<pre><code>bulkErrs = err.(*mgo.BulkError).Cases()
</code></pre>
<p>The type cast can fail, in which case, this panics</p>
<p>What you want to do is this:</p>
<pre><code>bulkErr, ok = err.(*mgo.BulkError)
if !ok {
// not a bulk error
}
for _, case := range bulkErr.Cases() {
//
}
</code></pre></pre>kidovate: <pre><p>This isn't so bad, you can do a type switch on your errors to get a catch type syntax. </p></pre>robe_and_wizard_hat: <pre><p>Yes, it's unfortunate. Perhaps bulk.Run() should have declared to return an <code>*mgo.BulkError</code> instead.</p></pre>euank: <pre><p>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.</p>
<p>Here's an example of how this can shoot you in the foot: <a href="https://play.golang.org/p/RBkfTmRQST" rel="nofollow">https://play.golang.org/p/RBkfTmRQST</a></p>
<p>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.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传