🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Error Boundaries

An error boundary is a guarded run of one task that reports a failure without stopping the other tasks. Each task runs inside its own pcall, so one failure stays inside its own run.

One failure does not stop the other tasks

The middle task fails, and the third task still runs.

local tasks = {function() return "a" end, function() error("bad", 0) end, function() return "c" end}
local done = {}
for i, task in ipairs(tasks) do
  local ok, result = pcall(task)
  if ok then done[#done + 1] = result end
end
print(table.concat(done, ","))

The boundary reports each failure

The failure list holds the position and the message of each failed task.

local tasks = {function() return "a" end, function() error("bad", 0) end, function() return "c" end}
local failures = {}
for i, task in ipairs(tasks) do
  local ok, err = pcall(task)
  if not ok then failures[#failures + 1] = i .. ":" .. err end
end
print(table.concat(failures, ","))

A boundary checks a traceback without printing it

The check asks whether the traceback holds the message, and prints only the answer.

local ok, err = pcall(function() error("disk full", 0) end)
print(ok)
print(string.find(debug.traceback(err), "disk full") ~= nil)

Example

local tasks = {function() return "one" end, function() error("no file", 0) end, function() return "three" end, function() error("no room", 0) end}
local passed = 0
local failures = {}
for i, task in ipairs(tasks) do
  local ok, result = pcall(task)
  if ok then passed = passed + 1 else failures[#failures + 1] = i .. ":" .. result end
end
print(passed)
print(table.concat(failures, ","))

Key points

  • Boundary: a pcall around a single task that turns its error into a value.
  • Isolation: a failing task does not stop the tasks after it.
  • Report: the boundary collects the error message for each failed task.
  • Task order: tasks still run in list order, failed or not.
  • Pass count: the boundary counts how many tasks succeeded.

In this example, four tasks run in list order inside their own guarded calls. Two succeed and two fail, so the pass count is two. The failure list names the failed positions and their messages.

Note

a boundary reports failures, it does not fix them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

The second of four tasks fails inside its boundary. How many tasks run after the failed one?