如何获取指向实际错误原因的堆栈跟踪 [英] How to get the stack trace pointing to actual error reason

查看:48
本文介绍了如何获取指向实际错误原因的堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些这样的代码:

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

如果err != nil我会得到这样的东西:

panic: some error explanation here

goroutine 1 [running]:
main.main()
    /tmp/blabla/main.go:6 +0x80

此堆栈跟踪完全合法,但是有时这些错误消息可能无法阐明发生了什么,因此我想更深入地研究第三方库的源代码,以调查究竟是什么导致该错误被返回.但是,当我的代码如此恐慌时,无法获得返回此错误的实际位置.

需要更多说明:当我来自抛出异常的JVM世界时,我可以完全跟踪抛出异常的确切代码行,从而可以轻松找到问题的所在并查看出了什么问题. Go堆栈跟踪恰好在我的代码恐慌的地方结束,因此在我的情况下不太有用.

我已经在此处创建了一个游乐场,理想情况下,我希望能够进行跟踪该错误实际上是从其返回的地方,而不是惊慌. (例如,第17行,return "", errors.New("some error explanation here"))

这有可能吗?

解决方案

简而言之:这是不可能的. 由于错误是值,因此不会对它们进行任何特殊处理.因此,当函数(通常)返回时,堆栈不再可用(即,另一个函数调用可能会覆盖返回错误函数的堆栈使用的内存).

go1.5引入了一个名为 trace 的工具,但目前尚无全面的教程,我发现其中任何一个都没有说要包含这种功能.

Let's say I have some code like this:

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

In case err != nil I will get something like this:

panic: some error explanation here

goroutine 1 [running]:
main.main()
    /tmp/blabla/main.go:6 +0x80

This stack trace is completely legit but sometimes these error messages may not clarify what happened and so I'd like to dig deeper into the source code of the 3rd party library to investigate what exactly causes this error to be returned. However when my code panics like this, there is no way to get the actual place that returned this error.

A little bit more clarification: as I'm coming from JVM world where exceptions are thrown I can completely trace what exactly line of code thrown the exception and thus can easily find the place and see what gone wrong. Go stack trace ends exactly where my code panics and thus not too useful in my case.

I've created a playground here and ideally I'd like to be able to trace the error to the place it was actually returned from, not panic. (e.g. to line 17, return "", errors.New("some error explanation here"))

Is this even possible?

解决方案

Shortly: this is not possible. Since errors are values, they are not treated in any special way. Due to this, when function (normally) returns, stack is no more available (ie. another function call may overwrite memory used by returning-error function' stack).

There is a tool called trace which was introduced with go1.5, but for now, there is no comprehensive tutorial available neither any of those I found says that this kind of feature will be included.

这篇关于如何获取指向实际错误原因的堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆