zoukankan      html  css  js  c++  java
  • Golang stackError 补充go错误定位能力力

         用过go的都知道,go的error实现很简单,errors.New实现的error类并不存储堆栈数据,这导致一个问题,就是多次error return后,或panic后recover了,找不到触发异常的位置,这导致问题排查进一步很难定位。stackError实现类似于 java中的exception类,里面可以存储堆栈数据,并且通过单向链表记录error的触发嵌套关系,使日志追踪变的更加容易!

    后来得天一个github.com/pkg/errors 很好实现堆栈追踪。

    另外配合http://github.com/lingdor/midlog 可以实现很好的日志记录功能

    1、stackError的引用

    go get 获取

    go get github.com/lingdor/stackerror

    go.mod

    require github.com/lingdor/stackerror 0.1.6
    go mod download

    2、堆栈定位

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

    输出:

    *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 )

    3、使用派生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 )


    4、优雅处理error

    //不用写哪么多if判断
    func main() {
    err := act1()
    stackerror.CheckPanic(err)
    }
    //可以日志清晰定位panic的位置
    
    func main() {
    defer func(){
    if err := recover();err!=nil {
    fmt.Println(err)
    }
    }()
    stackerror.Panic("here")
    } 
  • 相关阅读:
    hdu 3790 最短路径问题
    hdu 2112 HDU Today
    最短路问题 以hdu1874为例
    hdu 1690 Bus System Floyd
    hdu 2066 一个人的旅行
    hdu 2680 Choose the best route
    hdu 1596 find the safest road
    hdu 1869 六度分离
    hdu 3339 In Action
    序列化和反序列化
  • 原文地址:https://www.cnblogs.com/a-xu/p/11881148.html
Copyright © 2011-2022 走看看