What's the canonical way to differentiate errors?

blov · · 486 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>For example, you open a file and get back a PathError.</p> <p>How would you differentiate between (say) a file not found and a permission error.</p> <hr/>**评论:**<br/><br/>natefinch: <pre><p>This is the best guide I&#39;ve seen: <a href="https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully">https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully</a></p></pre>JackOhBlades: <pre><p>That post really helped me with Go&#39;s error handling. </p> <p>TLDR; check for the <em>behaviour</em> of the error, not the concrete type. </p> <pre><code>type Temporary interface { IsTemporary() bool } _, err := canFail(..) if temp, ok := err.(Temporary); ok { // handle the temporary error If temp.IsTemporary() { //... } } </code></pre> <p>Hope this helps!</p></pre>ragefacesmirk: <pre><p>The grpc library offers a good working example.</p></pre>jerf: <pre><p>Cast the error back into its underlying type (generally the two-argument form to avoid crashing if you are wrong), and then use whatever that type offers to determine the more-specific problem.</p> <p>If the type doesn&#39;t offer any useful methods or public fields, you are out of luck. That&#39;s why it&#39;s important to be careful with what errors you return; any data discarded by what you return stays discarded.</p></pre>riking27: <pre><p>The two-argument form looking like this:</p> <pre><code>if err, ok := err.(*os.PathError); ok { // ... check code ... } else if err != nil { // ... other errors ... } </code></pre></pre>tgaz: <pre><p>Type assertion as <a href="/u/jerf" rel="nofollow">/u/jerf</a> suggests.</p> <p>The other common way is to have a boolean function to identify classes of errors, like <a href="https://golang.org/pkg/os/#IsPermission" rel="nofollow">os.IsPermission</a>. Internally that could do whatever. In <code>os</code>, they look at errno values.</p></pre>natefinch: <pre><p>note there&#39;s an os.IsNotExist as well. These two functions are what you need for your specific case. In the general case, use Dave Cheney&#39;s handling errors by behavior. </p></pre>

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

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