Errors, Type Assertion, mgo.Bulk

polaris · · 733 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 &#34;err&#34; is &#34;error&#34;, 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 &#34;error&#34; 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&#39;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&#39;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&#39;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&#39;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&#39;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 &#39;case 2&#39; can be turned into &#39;case 3&#39; by some simple refactoring, so even if you start with correct code, it&#39;s basically a timebomb to define functions that return like that.</p></pre>

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

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