Lua中如何通过pcall获取错误的真实堆栈跟踪信息?
- 内容介绍
- 文章标签
- 相关推荐
本文共计453个文字,预计阅读时间需要2分钟。
对于我的pcall语句,我通常这样做:在局部状态中,err=pcall(fn),如果没有错误发生(即status为true),则不输出;如果发生错误,则打印出错误信息及调用栈。这种方法适用于处理一些基本操作,但问题是debug.stacktrace()返回的是相对于当前堆栈的跟踪信息。
所以对于我的pcall语句,我一直在做这样的事情local status, err = pcall(fn) if not status then print(err) print(debug.stacktrace()) end
这适用于一些基本的东西,但问题是debug.stacktrace()返回CURRENT相对堆栈跟踪,而不是错误的堆栈跟踪.如果fn中的错误在堆栈中发生了10级,那么我就不知道它究竟发生在哪里,只是这个pcall块失败了.我想知道是否有办法获得pcall的堆栈跟踪而不是当前的堆栈跟踪.我试过debug.stacktrace(错误),但它没有什么区别.
您需要使用xpcall提供自定义函数,该函数将堆栈跟踪添加到错误消息中. From PiL:Frequently, when an error happens, we want more debug information than
only the location where the error occurred. At least, we want a
traceback, showing the complete stack of calls leading to the error.
When pcall returns its error message, it destroys part of the stack
(the part that went from it to the error point). Consequently, if we
want a traceback, we must build it before pcall returns. To do that,
Lua provides the xpcall function. Besides the function to be called,
it receives a second argument, an error handler function. In case of
errors, Lua calls that error handler before the stack unwinds, so that
it can use the debug library to gather any extra information it wants
about the error.
您可以查看此patch that extends pcall to include stacktrace.
正如评论中所建议的那样,您可以使用本地ok,res = xpcall(f,debug.traceback,args …)与Lua 5.2或LuaJIT(打开Lua 5.2兼容性)并使用上面提到的Lua 5.1补丁.
本文共计453个文字,预计阅读时间需要2分钟。
对于我的pcall语句,我通常这样做:在局部状态中,err=pcall(fn),如果没有错误发生(即status为true),则不输出;如果发生错误,则打印出错误信息及调用栈。这种方法适用于处理一些基本操作,但问题是debug.stacktrace()返回的是相对于当前堆栈的跟踪信息。
所以对于我的pcall语句,我一直在做这样的事情local status, err = pcall(fn) if not status then print(err) print(debug.stacktrace()) end
这适用于一些基本的东西,但问题是debug.stacktrace()返回CURRENT相对堆栈跟踪,而不是错误的堆栈跟踪.如果fn中的错误在堆栈中发生了10级,那么我就不知道它究竟发生在哪里,只是这个pcall块失败了.我想知道是否有办法获得pcall的堆栈跟踪而不是当前的堆栈跟踪.我试过debug.stacktrace(错误),但它没有什么区别.
您需要使用xpcall提供自定义函数,该函数将堆栈跟踪添加到错误消息中. From PiL:Frequently, when an error happens, we want more debug information than
only the location where the error occurred. At least, we want a
traceback, showing the complete stack of calls leading to the error.
When pcall returns its error message, it destroys part of the stack
(the part that went from it to the error point). Consequently, if we
want a traceback, we must build it before pcall returns. To do that,
Lua provides the xpcall function. Besides the function to be called,
it receives a second argument, an error handler function. In case of
errors, Lua calls that error handler before the stack unwinds, so that
it can use the debug library to gather any extra information it wants
about the error.
您可以查看此patch that extends pcall to include stacktrace.
正如评论中所建议的那样,您可以使用本地ok,res = xpcall(f,debug.traceback,args …)与Lua 5.2或LuaJIT(打开Lua 5.2兼容性)并使用上面提到的Lua 5.1补丁.

