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补丁.