0Pricing
Lua Academy · Lesson

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 bad

debug.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)
end

All lessons in this course

  1. The error() Function
  2. Protected Calls with pcall
  3. xpcall and Message Handlers
  4. Structured Error Objects
← Back to Lua Academy