1. 程式人生 > 其它 >Go 裡的錯誤得這樣寫才優雅~

Go 裡的錯誤得這樣寫才優雅~

error

這個大家肯定使用過,標準庫的error錯誤實現比較簡單,無法進行堆疊追溯,對於產生錯誤時的上層呼叫者來講不是很友好,無法獲得錯誤的呼叫鏈詳細資訊。

//不帶堆疊
err:=errors.New("errormsg")
fmt.Printf("%+v\n",err)

//輸出
errormsg

pkg/errors

github.com/pkg/errors支援堆疊資訊,可以獲得錯誤的呼叫鏈詳細資訊。

普通的

//帶堆疊
err:=errors.New("errormsg")
fmt.Printf("%+v\n",err)

//輸出
errormsg
main.main
/Users/xinliang/go/project/demo/err/err.go:14
runtime.main
/usr/local/go/src/runtime/proc.go:225
runtime.goexit
/usr/local/go/src/runtime/asm_amd64.s:1371

帶堆疊,包裝描述

err:=errors.Wrap(errerror,messagestring)



err:=errors.Wrapf(errerror,formatstring,args...interface{})

帶堆疊,不包裝描述

err:=errors.WithStack(errerror)

不帶堆疊,包裝描述

err:=errors.WithMessage(errerror,messagestring)



err:=errors.WithMessagef(errerror,formatstring,args...interface{})

思考

大家想一想,我們在使用pkg/errors

時,會遇到什麼問題?

會遇到堆疊資訊重複的問題!

比如,一個方法的呼叫鏈路比較長,就會出現這種情況,舉個例子:

funcmain(){
err:=func1()
fmt.Printf("%+v\n",errors.Wrapf(err,"func1erroroccurred"))
}

funcfunc1()error{
err:=func2()
returnerrors.Wrapf(err,"func2erroroccurred")
}

funcfunc2()error{
err:=errors.New("errormsg")
returnerr
}

想想看,會打印出什麼?

是不是發現打印出的堆疊資訊有重複的?