回答

收藏

如何让 Golang 程序打印它刚刚调用的错误的行号?

技术问答 技术问答 252 人阅读 | 0 人回复 | 2023-09-12

我试着在我的 Golang 在程序中出错,log.Fatal但是,log.Fatal没有打印行log.Fatal。有没有办法访名叫  log.Fatal 行号?也就是说,抛错时有没有办法获得行号?9 i' h& Y! Y( k0 x( S% L
我试图谷歌,但我不确定。我能得到的最好的是打印堆栈跟踪。我觉得很好,但可能有点太多了。debug.PrintStack()每次需要行号时都写,我只是很惊讶没有任何内置函数用于此之类的log.FatalStackTrace()或非服装的东西。1 I. v& v: Q& o: e! \. {, A. T
此外,我之所以不想制作自己的调试/错误处理内容,是因为我不想让人们学习如何使用我的特殊服装处理代码。我只是想要一些标准的东西。人们以后可以读我的代码,就像
9 s: z$ t" Y: D/ A( g9 G7 z$ u好吧,所以它抛出错误并执行 X…”
. u2 \% V$ p& o5 ~+ {) [
了解我代码的人越少越好: ^* m) o  m4 b# }
                                                               
$ u6 a# D/ X, n# y, s" ]9 C% k    解决方案:                                                               
1 x& V. u- @2 N/ x7 S% q                                                                你可以用最小的学习曲线来实现它 runtime.Caller
1 K( |3 ^. r: q0 [) h/ Y7 I! V[code]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")  code]
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则