I created something that generates a stack trace for an error using the functions error and xpcall. This is impossible to do using the regular pcall or ypcall. This means, unfortunately, that I cannot currently generate a stack trace for functions that yield (for example by using wait).
Therefore, I request an yxpcall (yielding xpcall) function that yields correctly like ypcall, but lets you use your own error handler like xpcall.
Here's the code I used:
function HandleError(errorMessage)
local buffer = {errorMessage}
local trace = StackTrace(5)
for index, details in ipairs(trace) do
table.insert(buffer, string.format("Script '%s', Line %d", details[1], details[2]))
end
table.insert(buffer, "stack end")
return table.concat(buffer, "\n")
end
function StackTrace(level)
local trace = {}
while true do
local success, errorMessage = pcall(error, "-", level)
if errorMessage == "-" then
return trace
else
local script, line = string.match(errorMessage, "(.*):(%d+)")
table.insert(trace, {script, tonumber(line)})
level = level + 1
end
end
end
function F1()
error("Test")
end
function F2()
F1()
end
function F3()
F2()
end
function F4()
F3()
end
local success, errorMessage = xpcall(F4, HandleError)
print(errorMessage)
--[[
Output:
Workspace.Stack Trace:25: Test
Script 'Workspace.Stack Trace', Line 25
Script 'Workspace.Stack Trace', Line 28
Script 'Workspace.Stack Trace', Line 31
Script 'Workspace.Stack Trace', Line 34
stack end
]]-- |