How to get the stack trace pointing to actual error reason

前端 未结 8 1684
夕颜
夕颜 2020-12-18 19:42

Let\'s say I have some code like this:

value, err := some3rdpartylib.DoSomething()
if err != nil {
    panic(err)
}

In case err != ni

8条回答
  •  隐瞒了意图╮
    2020-12-18 20:17

    Take a look at https://github.com/ztrue/tracerr

    I created this package in order to have both stack trace and source fragments to be able to debug faster and log errors with much more details.

    Here is a code example:

    package main
    
    import (
        "io/ioutil"
        "github.com/ztrue/tracerr"
    )
    
    func main() {
        if err := read(); err != nil {
            tracerr.PrintSourceColor(err)
        }
    }
    
    func read() error {
        return readNonExistent()
    }
    
    func readNonExistent() error {
        _, err := ioutil.ReadFile("/tmp/non_existent_file")
        // Add stack trace to existing error, no matter if it's nil.
        return tracerr.Wrap(err)
    }
    

    And here is the output:

提交回复
热议问题