从现状谈起
Go语言受到诟病最多的一项就是其错误处理机制。如果显式地检查和处理每个error,这恐怕的确会让人望而却步。下面我们将给大家介绍Go语言中如何更优雅的错误处理。
Golang 中的错误处理原则,开发者曾经之前专门发布了几篇文章( Error handling and Go 和 Defer, Panic, and Recover、Errors are values )介绍。分别介绍了 Golang 中处理一般预知到的错误与遇到崩溃时的错误处理机制。
一般情况下,我们还是以官方博客中的错误处理例子为例:
func main() {
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
// 或者更简单的:
// return err
}
...
}
当然对于简化代码行数,还有另外一种写法:
func main() {
...
if f, err = os.Open("filename.ext"); err != nil{
log.Fatal(err)
}
...
}
正常情况下,Golang 现有的哲学中,要求你尽量手工处理所有的错误返回,这稍微增加了开发人员的心智负担。关于这部分设计的讨论,请参考本文最开始提供的参考链接,此处不做太多探讨。
本质上,Golang 中的错误类型 error 是一个接口类型:
type error interface {
Error() string
}
只要满足这一接口定义的所有数值都可以传入 error 类型的位置。在 Go Proverbs 中也提到了关于错误的描述: Errors are values。这一句如何理解呢?
Errors are values
事实上,在实际使用过程中,你可能也发现了对 Golang 而言,所有的信息是非常不足的。比如下面这个例子:
buf := make([]byte, 100)
n, err := r.Read(buf)
buf = buf[:n]
if err == io.EOF {
log.Fatal("read failed:", err)
}
事实上这只会打印信息 2017/02/08 13:53:54 read failed:EOF,这对我们真实环境下的错误调试与分析其实是并没有任何意义的,我们在查看日志获取错误信息的时候能够获取到的信息十分有限。
于是乎,一些提供了上下文方式的一些错误处理形式便在很多类库中非常常见:
err := os.Remove("/tmp/nonexist")
log.Println(err)
输出了:
2017/02/08 14:09:22 remove /tmp/nonexist: no such file or directory
这种方式提供了一种更加直观的上下文信息,比如具体出错的内容,也可以是出现错误的文件等等。通过查看Remove的实现,我们可以看到:
// PathError records an error and the operation and file path that caused it.
type PathError struct {
Op string
Path string
Err error
}
func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
// file_unix.go 针对 *nix 系统的实现
// Remove removes the named file or directory.
// If there is an error, it will be of type *PathError.
func Remove(name string) error {
// System call interface forces us to know
// whether name is a file or directory.
// Try both: it is cheaper on average than
// doing a Stat plus the right one.
e := syscall.Unlink(name)
if e == nil {
return nil
}
e1 := syscall.Rmdir(name)
if e1 == nil {
return nil
}
// Both failed: figure out which error to return.
// OS X and Linux differ on whether unlink(dir)
// returns EISDIR, so can't use that. However,
// both agree that rmdir(file) returns ENOTDIR,
// so we can use that to decide which error is real.
// Rmdir might also return ENOTDIR if given a bad
// file path, like /etc/passwd/foo, but in that case,
// both errors will be ENOTDIR, so it's okay to
// use the error from unlink.
if e1 != syscall.ENOTDIR {
e = e1
}
return &PathError{"remove", name, e}
}










