Golang stackError 補充go錯誤定位能力

     用過go的都知道,go的error實現很簡單,errors.New實現的error類並不存儲堆棧數據,這致使一個問題,就是屢次error return後,或panic後recover了,找不到觸發異常的位置,這致使問題排查進一步很難定位。stackError實現相似於 java中的exception類,裏面能夠存儲堆棧數據,而且經過單向鏈表記錄error的觸發嵌套關係,使日誌追蹤變的更加容易!java

一、stackError的引用

go get 獲取git

go get github.com/lingdor/stackError

go.modgithub

require github.com/lingdor/stackError 0.1.5
go mod download

二、堆棧定位

func act1()error {
return stackError.New("here Error")
}
func main(){
err:=act1()
fmt.println(err.Error())
}

 

輸出:ui

*stackError.stackError : here Error
at main.act1( /Users/user/go/testMain/src/main/main.go:17 )
at main.main( /Users/user/go/testMain/src/main/main.go:22 )
at runtime.main( /usr/local/Cellar/go/1.13.4/libexec/src/runtime/proc.go:203 )spa

三、使用派生error

func act1() error {
return stackError.New("here Error")
}
func main() {

er := act1()
ParentErr := stackError.NewParent("act1 error", er)
fmt.Println(ParentErr.Error())
}

輸出:日誌

*stackError.stackError : act1 error
at main.main( /Users/user/go/testMain/main.go:22 )
at runtime.main( /usr/local/Cellar/go/1.13.4/libexec/src/runtime/proc.go:203 )
*stackError.stackError : here Error
at main.act1( /Users/user/go/testMain/main.go:16 )
at main.main( /Users/user/go/testMain/main.go:21 )
at runtime.main( /usr/local/Cellar/go/1.13.4/libexec/src/runtime/proc.go:203 )code


四、優雅處理errorblog

//不用寫哪麼多if判斷
func main() {
err := act1()
stackError.CheckPanic(err)
}
//能夠日誌清晰定位panic的位置

func main() {
defer func(){
if err := recover();err!=nil {
fmt.Println(err)
}
}()
stackError.Panic("here")
} 
相關文章
相關標籤/搜索