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")
    } 
  • 相关阅读:
    java泛型的一些知识点:Java泛型--泛型应用--泛型接口、泛型方法、泛型数组、泛型嵌套
    Java遍历Map的四种方式
    Less20、21、22【报错注入+Cookie字段注入+Base64编码】
    Less18、19【报错注入+User-Agent、Referer字段注入】
    Less17【报错注入+Update注入/时间注入】
    Less-16【盲注+时间注入】
    Less-15【盲注+时间注入】
    Less-14【报错注入】
    Less-12、13【报错注入】
    Less-11【报错注入】
  • 原文地址:https://www.cnblogs.com/a-xu/p/11881148.html
Copyright © 2011-2022 走看看