0Pricing
Lua Academy · Lesson

Structured Error Objects

Pass tables as error objects to convey type and context.

Why Structured Errors?

Plain string errors are hard to handle programmatically. Structured error objects (tables) carry type information, context data, and can be inspected and acted upon by callers. This enables error-based dispatch without string parsing.

-- Plain string: hard to handle programmatically
error("database error: connection refused")

-- Structured: type + data
error({
  type = "DatabaseError",
  code = "CONN_REFUSED",
  host = "localhost",
  port = 5432,
  message = "connection refused"
})

Error Constructor Pattern

Create an error factory function for each error type. The factory builds a table with consistent fields: type, message, and any relevant context. A __tostring metamethod makes the error print nicely.

local ErrorMT = {__tostring = function(e)
  return string.format("[%s] %s", e.type, e.message)
end}

local function makeError(errType, msg, data)
  local e = {type=errType, message=msg}
  if data then for k,v in pairs(data) do e[k]=v end end
  return setmetatable(e, ErrorMT)
end

local E = {
  notFound = function(name) return makeError("NOT_FOUND","not found: "..name,{name=name}) end,
  badInput = function(msg,field) return makeError("BAD_INPUT",msg,{field=field}) end,
}

local ok, err = pcall(error, E.notFound("user:42"))
print(tostring(err))   -- [NOT_FOUND] not found: user:42

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