從現(xiàn)狀談起
Go語言受到詬病最多的一項就是其錯誤處理機制。如果顯式地檢查和處理每個error,這恐怕的確會讓人望而卻步。下面我們將給大家介紹Go語言中如何更優(yōu)雅的錯誤處理。
Golang 中的錯誤處理原則,開發(fā)者曾經(jīng)之前專門發(fā)布了幾篇文章( 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
}
...
}
當然對于簡化代碼行數(shù),還有另外一種寫法:
func main() {
...
if f, err = os.Open("filename.ext"); err != nil{
log.Fatal(err)
}
...
}
正常情況下,Golang 現(xiàn)有的哲學中,要求你盡量手工處理所有的錯誤返回,這稍微增加了開發(fā)人員的心智負擔。關于這部分設計的討論,請參考本文最開始提供的參考鏈接,此處不做太多探討。
本質上,Golang 中的錯誤類型 error 是一個接口類型:
type error interface {
Error() string
}
只要滿足這一接口定義的所有數(shù)值都可以傳入 error 類型的位置。在 Go Proverbs 中也提到了關于錯誤的描述: Errors are values。這一句如何理解呢?
Errors are values
事實上,在實際使用過程中,你可能也發(fā)現(xiàn)了對 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
,這對我們真實環(huán)境下的錯誤調試與分析其實是并沒有任何意義的,我們在查看日志獲取錯誤信息的時候能夠獲取到的信息十分有限。
于是乎,一些提供了上下文方式的一些錯誤處理形式便在很多類庫中非常常見:
err := os.Remove("/tmp/nonexist")
log.Println(err)
輸出了:
2017/02/08 14:09:22 remove /tmp/nonexist: no such file or directory
這種方式提供了一種更加直觀的上下文信息,比如具體出錯的內容,也可以是出現(xiàn)錯誤的文件等等。通過查看Remove的實現(xiàn),我們可以看到:
// 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 系統(tǒng)的實現(xiàn)
// 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}
}
實際上這里 Golang 標準庫中返回了一個名為 PathError 的結構體,這個結構體定義了操作類型、路徑和原始的錯誤信息,然后通過 Error 方法對所有信息進行了整合。
但是這樣也會存在問題,比如需要進行單獨類型復雜的分類處理,比如上面例子中,需要單獨處理 PathError 這種問題,你可能需要一個單獨的類型推導:
err := xxxx()
if err != nil {
swtich err := err.(type) {
case *os.PathError:
...
default:
...
}
}
這樣反倒會增加錯誤處理的復雜度。同時,這些錯誤必須變?yōu)閷С鲱愋停矔黾诱麄€系統(tǒng)的復雜度。
另外一個問題是,我們在出現(xiàn)錯誤時,我們通常也希望獲取更多的堆棧信息,方便我們進行后續(xù)的故障追蹤。在現(xiàn)有的錯誤體系中,這相對比較復雜:你很難通過一個接口類型獲取完整的調用堆棧。這時,我們可能就需要一個第三方庫區(qū)去解決遇到的這些錯誤處理問題。
還有一種情況是,我們希望在錯誤處理過程中同樣可以附加一些信息,這些也會相對比較麻煩。
更優(yōu)雅的錯誤處理
之前提到了多種實際應用場景中出現(xiàn)的錯誤處理方法和遇到的一些問題,這里推薦使用第三方庫去解決部分問題:github.com/pkg/errors
。
比如當我們出現(xiàn)問題時,我們可以簡單的使用 errors.New
或者 errors.Errorf
生成一個錯誤變量:
err := errors.New("whoops")
// or
err := errors.Errorf("whoops: %s", "foo")
當我們需要附加信息時,則可以使用:
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
當需要獲取調用堆棧時,則可以使用:
err := errors.New("whoops")
fmt.Printf("%+v", err)
其他建議
在上面做類型推導時,我們發(fā)現(xiàn)在處理一類錯誤時可能需要多個錯誤類型,這可能在某些情況下相對來說比較復雜,很多時候我們可以使用接口形式去方便處理:
type temporary interface {
Temporary() bool
}
// IsTemporary returns true if err is temporary.
func IsTemporary(err error) bool {
te, ok := errors.Cause(err).(temporary)
return ok te.Temporary()
}
這樣就可以提供更加方便的錯誤解析和處理。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
您可能感興趣的文章:- GO語言標準錯誤處理機制error用法實例
- Golang巧用defer進行錯誤處理的方法
- 詳解Go多協(xié)程并發(fā)環(huán)境下的錯誤處理
- Go語言中錯誤處理實例分析
- Go 自定義error錯誤的處理方法
- Golang中重復錯誤處理的優(yōu)化方法
- 一些關于Go程序錯誤處理的相關建議