How do you get a Golang program to print the line number of the error it just called?

后端 未结 3 518
南方客
南方客 2020-12-12 12:40

I was trying to throw errors in my Golang program with log.Fatal but, log.Fatal does not also print the line where the log.Fatal was r

3条回答
  •  臣服心动
    2020-12-12 13:12

    If you need exactly a stack trace, 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:

提交回复
热议问题