Pin*_*hio 78 error-handling go
我试图在我的Golang程序中抛出错误log.Fatal但是,log.Fatal也没有打印出log.Fatal运行的行.有没有办法访问调用log.Fatal的行号?即,有什么方法可以在抛出错误时获取行号?
我试图谷歌这个,但不确定如何.我能得到的最好的东西是打印堆栈跟踪,我认为它很好但可能有点太多了.debug.PrintStack()每次我需要行号时我也不想写,我很惊讶没有任何内置功能,log.FatalStackTrace()或者不是服装的东西.
另外,我不想自己进行调试/错误处理的原因是因为我不希望人们必须学习如何使用我的特殊服装处理代码.我只想要一些标准的东西,人们可以在以后阅读我的代码,就像
"啊好的,所以它抛出一个错误并做X ......"
人们越少了解我的代码越好:)
Jim*_*imB 102
您可以在自定义Logger上设置Flags,或者将默认设置为include Llongfile或Lshortfile
// to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)
One*_*One 78
精简版, 没有直接内置的东西但是,您可以使用最小的学习曲线来实现它 runtime.Caller
func HandleError(err error) (b bool) {
    if err != nil {
        // notice that we're using 1, so it will actually log where
        // the error happened, 0 = this function, we don't want that.
        _, fn, line, _ := runtime.Caller(1)
        log.Printf("[error] %s:%d %v", fn, line, err)
        b = true
    }
    return
}
//this logs the function name as well.
func FancyHandleError(err error) (b bool) {
    if err != nil {
        // notice that we're using 1, so it will actually log the where
        // the error happened, 0 = this function, we don't want that.
        pc, fn, line, _ := runtime.Caller(1)
        log.Printf("[error] in %s[%s:%d] %v", runtime.FuncForPC(pc).Name(), fn, line, err)
        b = true
    }
    return
}
func main() {
    if FancyHandleError(fmt.Errorf("it's the end of the world")) {
        log.Print("stuff")
    }
}
小智 7
如果您确实需要堆栈跟踪,请查看https://github.com/ztrue/tracerr
我创建这个包是为了拥有堆栈跟踪和源代码片段,以便能够更快地调试并记录更多详细信息的错误。
这是一个代码示例:
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)
}