從現(xiàn)狀談起
Go語(yǔ)言受到詬病最多的一項(xiàng)就是其錯(cuò)誤處理機(jī)制。如果顯式地檢查和處理每個(gè)error,這恐怕的確會(huì)讓人望而卻步。下面我們將給大家介紹Go語(yǔ)言中如何更優(yōu)雅的錯(cuò)誤處理。
Golang 中的錯(cuò)誤處理原則,開(kāi)發(fā)者曾經(jīng)之前專門發(fā)布了幾篇文章( Error handling and Go 和 Defer, Panic, and Recover、Errors are values )介紹。分別介紹了 Golang 中處理一般預(yù)知到的錯(cuò)誤與遇到崩潰時(shí)的錯(cuò)誤處理機(jī)制。
一般情況下,我們還是以官方博客中的錯(cuò)誤處理例子為例:
func main() { f, err := os.Open("filename.ext") if err != nil { log.Fatal(err) // 或者更簡(jiǎn)單的: // return err } ... }
當(dāng)然對(duì)于簡(jiǎn)化代碼行數(shù),還有另外一種寫法:
func main() { ... if f, err = os.Open("filename.ext"); err != nil{ log.Fatal(err) } ... }
正常情況下,Golang 現(xiàn)有的哲學(xué)中,要求你盡量手工處理所有的錯(cuò)誤返回,這稍微增加了開(kāi)發(fā)人員的心智負(fù)擔(dān)。關(guān)于這部分設(shè)計(jì)的討論,請(qǐng)參考本文最開(kāi)始提供的參考鏈接,此處不做太多探討。
本質(zhì)上,Golang 中的錯(cuò)誤類型 error 是一個(gè)接口類型:
type error interface { Error() string }
只要滿足這一接口定義的所有數(shù)值都可以傳入 error 類型的位置。在 Go Proverbs 中也提到了關(guān)于錯(cuò)誤的描述: Errors are values。這一句如何理解呢?
Errors are values
事實(shí)上,在實(shí)際使用過(guò)程中,你可能也發(fā)現(xiàn)了對(duì) Golang 而言,所有的信息是非常不足的。比如下面這個(gè)例子:
buf := make([]byte, 100) n, err := r.Read(buf) buf = buf[:n] if err == io.EOF { log.Fatal("read failed:", err) }
事實(shí)上這只會(huì)打印信息 2017/02/08 13:53:54 read failed:EOF
,這對(duì)我們真實(shí)環(huán)境下的錯(cuò)誤調(diào)試與分析其實(shí)是并沒(méi)有任何意義的,我們?cè)诓榭慈罩精@取錯(cuò)誤信息的時(shí)候能夠獲取到的信息十分有限。
于是乎,一些提供了上下文方式的一些錯(cuò)誤處理形式便在很多類庫(kù)中非常常見(jiàn):
err := os.Remove("/tmp/nonexist") log.Println(err)
輸出了:
2017/02/08 14:09:22 remove /tmp/nonexist: no such file or directory
這種方式提供了一種更加直觀的上下文信息,比如具體出錯(cuò)的內(nèi)容,也可以是出現(xiàn)錯(cuò)誤的文件等等。通過(guò)查看Remove的實(shí)現(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 針對(duì) *nix 系統(tǒng)的實(shí)現(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} }
實(shí)際上這里 Golang 標(biāo)準(zhǔn)庫(kù)中返回了一個(gè)名為 PathError 的結(jié)構(gòu)體,這個(gè)結(jié)構(gòu)體定義了操作類型、路徑和原始的錯(cuò)誤信息,然后通過(guò) Error 方法對(duì)所有信息進(jìn)行了整合。
但是這樣也會(huì)存在問(wèn)題,比如需要進(jìn)行單獨(dú)類型復(fù)雜的分類處理,比如上面例子中,需要單獨(dú)處理 PathError 這種問(wèn)題,你可能需要一個(gè)單獨(dú)的類型推導(dǎo):
err := xxxx() if err != nil { swtich err := err.(type) { case *os.PathError: ... default: ... } }
這樣反倒會(huì)增加錯(cuò)誤處理的復(fù)雜度。同時(shí),這些錯(cuò)誤必須變?yōu)閷?dǎo)出類型,也會(huì)增加整個(gè)系統(tǒng)的復(fù)雜度。
另外一個(gè)問(wèn)題是,我們?cè)诔霈F(xiàn)錯(cuò)誤時(shí),我們通常也希望獲取更多的堆棧信息,方便我們進(jìn)行后續(xù)的故障追蹤。在現(xiàn)有的錯(cuò)誤體系中,這相對(duì)比較復(fù)雜:你很難通過(guò)一個(gè)接口類型獲取完整的調(diào)用堆棧。這時(shí),我們可能就需要一個(gè)第三方庫(kù)區(qū)去解決遇到的這些錯(cuò)誤處理問(wèn)題。
還有一種情況是,我們希望在錯(cuò)誤處理過(guò)程中同樣可以附加一些信息,這些也會(huì)相對(duì)比較麻煩。
更優(yōu)雅的錯(cuò)誤處理
之前提到了多種實(shí)際應(yīng)用場(chǎng)景中出現(xiàn)的錯(cuò)誤處理方法和遇到的一些問(wèn)題,這里推薦使用第三方庫(kù)去解決部分問(wèn)題:github.com/pkg/errors
。
比如當(dāng)我們出現(xiàn)問(wèn)題時(shí),我們可以簡(jiǎn)單的使用 errors.New
或者 errors.Errorf
生成一個(gè)錯(cuò)誤變量:
err := errors.New("whoops") // or err := errors.Errorf("whoops: %s", "foo")
當(dāng)我們需要附加信息時(shí),則可以使用:
cause := errors.New("whoops") err := errors.Wrap(cause, "oh noes")
當(dāng)需要獲取調(diào)用堆棧時(shí),則可以使用:
err := errors.New("whoops") fmt.Printf("%+v", err)
其他建議
在上面做類型推導(dǎo)時(shí),我們發(fā)現(xiàn)在處理一類錯(cuò)誤時(shí)可能需要多個(gè)錯(cuò)誤類型,這可能在某些情況下相對(duì)來(lái)說(shuō)比較復(fù)雜,很多時(shí)候我們可以使用接口形式去方便處理:
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() }
這樣就可以提供更加方便的錯(cuò)誤解析和處理。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流。
標(biāo)簽:駐馬店 昭通 泰安 滄州 瀘州 阿壩 晉中 東營(yíng)
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語(yǔ)言中更優(yōu)雅的錯(cuò)誤處理》,本文關(guān)鍵詞 語(yǔ),言中,更,優(yōu)雅,的,錯(cuò)誤,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。