xpcall and Message Handlers
Use xpcall with a custom handler for detailed error tracebacks.
xpcall Syntax
xpcall(f, handler, ...) calls f with arguments ... in protected mode, and on error calls handler(errorObject). The handler's return value becomes the second return value of xpcall. Unlike pcall, xpcall runs the handler while the stack is intact.
local function handler(err)
return "HANDLED: " .. tostring(err)
end
local ok, msg = xpcall(
function() error("something bad") end,
handler
)
print(ok) -- false
print(msg) -- HANDLED: ...: something baddebug.traceback as Handler
The most common xpcall handler is debug.traceback. Pass it directly as the handler — it formats the error with a full call stack trace, invaluable for debugging production errors.
local function level3() error("deep error") end
local function level2() level3() end
local function level1() level2() end
local ok, err = xpcall(level1, debug.traceback)
if not ok then
-- err contains the full stack trace
print(err)
endAll lessons in this course
- The error() Function
- Protected Calls with pcall
- xpcall and Message Handlers
- Structured Error Objects