TExcelTAD
Home › Lua › Lua Error Handling

Lua Error Handling

When something goes wrong, Lua raises an error, which stops the current code and unwinds the call stack. If nothing catches it, the program stops with a message. You catch errors with pcall ("protected call"), raise them with error, and check conditions with assert.

Raising errors

error(message) raises an error. With a string message, Lua adds the position (file and line) of the code that raised it:

lua · try it yourself
local function withdraw(balance, amount)
  if amount > balance then
    error("insufficient funds")
  end
  return balance - amount
end

local ok, err = pcall(withdraw, 50, 80)
print(ok, err)
print(pcall(withdraw, 50, 20))
false	/app/output.s:3: insufficient funds
true	30

pcall(f, args…) calls f and returns true plus f's results on success, or false plus the error value on failure. The program keeps running either way.

Note: The playground stores your code as /app/output.s, so that is the file name in error positions. On your own machine you would see your file name, such as bank.lua:3:.

The level argument

error(msg, level) controls whose position is added. Level 1 (default) is the function that called error; level 2 blames its caller, which is right for argument checks; level 0 adds no position at all:

lua · try it yourself
local function setVolume(v)
  if type(v) ~= "number" then
    error("volume must be a number, got " .. type(v), 2)
  end
  return v
end

local ok, err = pcall(function()
  setVolume("loud")            -- line 9: this is the line that gets blamed
end)
print(err)
print(select(2, pcall(error, "no position", 0)))
/app/output.s:9: volume must be a number, got string
no position

Error objects

The error value doesn't have to be a string. Raising a table lets callers inspect structured information (no position is added to tables):

lua · try it yourself
local function parsePort(text)
  local n = tonumber(text)
  if not n then
    error({ code = "EINVAL", message = "not a number: " .. text })
  end
  if n < 1 or n > 65535 then
    error({ code = "ERANGE", message = "port out of range: " .. n })
  end
  return n
end

for _, input in ipairs({ "8080", "http", "70000" }) do
  local ok, result = pcall(parsePort, input)
  if ok then
    print("port", result)
  else
    print(result.code, result.message)
  end
end
port	8080
EINVAL	not a number: http
ERANGE	port out of range: 70000

assert

assert(value, message) raises an error with message if value is falsy; otherwise it returns all its arguments. It pairs perfectly with functions that return nil, err. Like error, it adds the position to a string message:

lua · try it yourself
local function loadConfig(name)
  if name ~= "app.conf" then
    return nil, "cannot open " .. name
  end
  return { debug = true }
end

local config = assert(loadConfig("app.conf"))
print(config.debug)

local ok, err = pcall(function() return assert(loadConfig("missing.conf")) end)
print(ok, err)
print(pcall(assert, 1 == 2))
true
false	/app/output.s:11: cannot open missing.conf
false	assertion failed!

xpcall and message handlers

xpcall(f, handler, args…) works like pcall but calls handler(err) before the stack unwinds. The handler can add context or call debug.traceback(err) to get a full stack trace for logs:

lua · try it yourself
local function risky(n)
  local data = nil
  return data[n]               -- indexing nil fails
end

local function handler(err)
  return "handled: " .. tostring(err)
end

print(xpcall(risky, handler, 3))
print(xpcall(function() return "fine" end, handler))
false	handled: /app/output.s:3: attempt to index a nil value (local 'data')
true	fine

Built-in runtime errors

Message Typical cause
attempt to index a nil value (local 'x') using x.field when x is nil (a misspelt name, a missing key, . instead of :)
attempt to call a nil value (global 'foo') calling a function that doesn't exist
attempt to perform arithmetic on a nil value a variable that was never set
attempt to concatenate a nil value .. with nil (use tostring)
attempt to compare number with nil < with a missing value
bad argument #1 to 'insert' (table expected, got nil) wrong argument to a library function

Cleaning up with

A local with the <close> attribute calls its value's __close metamethod when it goes out of scope, even when an error is raised. This is Lua 5.4's answer to finally/using:

lua · try it yourself
local function openResource(name)
  return setmetatable({ name = name }, {
    __close = function(res, err)
      print("closing " .. res.name .. (err and " after error" or ""))
    end,
  })
end

local function work(fail)
  local res <close> = openResource("db")
  print("working with " .. res.name)
  if fail then error("query failed", 0) end
  return "ok"
end

print(pcall(work, false))
print(pcall(work, true))
working with db
closing db
true	ok
working with db
closing db after error
false	query failed

Test yourself

What does pcall(f) return when f raises an error?

  1. nil
  2. false and the error value
  3. It re-raises the error
  4. true and nil

Which error level blames the caller of the current function?

  1. 0
  2. 1
  3. 2
  4. -1

What does assert(x, "msg") return when x is truthy?

  1. true
  2. Nothing
  3. All its arguments (x, "msg")
  4. "msg"