LU

Lua Error Handling

Lua error handling using pcall, xpcall, custom error objects, and propagation patterns

Details

Language / Topic
luaLua
Category
Error Handling

Rules

balanced
- Use `local ok, err = pcall(f, args)` to call functions that may raise errors — check `ok` before using the result.
- Use `xpcall(f, handler, args)` when you need a stack traceback — pass `debug.traceback` as the handler for rich error output.
- Raise errors with `error({code = 'NOT_FOUND', msg = 'item missing'}, 2)` using a table object so callers can inspect fields programmatically.
- Pass a level argument to `error(msg, level)` — level 2 attributes the error to the caller rather than the function raising it.
- Use structured error tables (`{type = 'IOError', message = '...', cause = original_err}`) for errors that cross module boundaries.
- Return `nil, 'error message'` (the two-value convention) for expected failures in library functions — reserve `error()` for unexpected states.
- Check all `io.*` and `os.*` calls with `if not result then error(err_msg) end` — they return `nil, msg` on failure.