- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我如何处理 Go 中的大量错误?
我查看我的代码,发现它充满了错误处理程序:
err = result.Scan(&bot.BID, &bot.LANGUAGE, &bot.SOURCE)
if err != nil {
log.Fatalf("result.Scan: %v", err)
return
}
fileName, err := copySourceToTemporaryFile(bot)
if err != nil {
log.Fatalf("copySourceToTemporaryFile: %v", err)
return
}
...
很多行看起来像:
// do something
// handle error
// handle error
// handle error
// do something 2
// handle error
// handle error
// handle error
我能否创建一个打印错误并停止处理的默认处理程序,或者至少从我的代码逻辑中移出这个“错误处理程序垃圾”?
最佳答案
这让我想起了最近的 Errors are values Rob Pike 以及 Mr. Rob Pike taught me about practice of error handling in Go at GoCon 2014
The key lesson, however, is that errors are values and the full power of the Go programming language is available for processing them.
It's worth stressing that whatever the design, it's critical that the program check the errors however they are exposed. The discussion here is not about how to avoid checking errors, it's about using the language to handle errors with grace.
一种技术是定义一个名为 errWriter
的对象:
type errWriter struct {
w io.Writer
err error
}
The
write
method calls the Write method of the underlyingWriter
and records the first error for future reference:
func (ew *errWriter) write(buf []byte) {
if ew.err != nil {
return
}
_, ew.err = ew.w.Write(buf)
}
As soon as an error occurs, the
write
method becomes a no-op but theerror
value is saved.Given the
errWriter
type and its write method, the code above can be refactored:
ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
return ew.err
}
关于error-handling - Go 中更简洁的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28409118/
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我是 Dapper 的新手我正在尝试了解它实际上是如何映射事物的。我有以下数据库结构: calendar | Id | Name | meeting_room | Id | Calendar_id
抱歉问题标题很糟糕。有没有办法在一行中做到这一点: Button button = (Button)Gridview.Cells[0].FindControl("controlname"); butt
在 Java 中在声明点和使用点声明列表/数组文字的tersest方法是什么? 作为次要问题,我更喜欢一种不会导致编译时警告或要求抑制警告的方法。 注意:就我个人而言,这是针对Java 8ish on
什么是现代、简洁、快速的方法来测试节点是否有任何与给定选择器匹配的子节点? “简洁”是指类似于 jQuery 或函数式风格,例如避免循环。我知道本地选择器越来越多地使用这种类型的东西,但没有跟上发展的
getFirstNotNullResult 执行函数列表,直到其中一个函数返回非空值。 如何更优雅/简洁地实现 getNotNullFirstResult? object A { def main
根据 stackoverflow 上某人的推荐,我使用了 jquery succint https://github.com/micjamking/Succinct截断我在 php 网站上的帖子。 它
我是一名优秀的程序员,十分优秀!