Handling errors with pcall, xpcall, and assert
By default, the Lua language uses its internal error function. If an error occurs, Lua will usually abort code execution and put the error message with trace back into the standard error output. You can override the standard behavior with the pcall
and xpcall
functions. The main difference between these two functions is that pcall
will return the status code and error message as the second return value, and xpcall
will use the user-defined error function.
This way you can catch nonfatal errors and emulate the try
and catch
block.
Getting ready
This recipe will show error handling on a simple function that can exit prematurely with the error message:
local function f1(a, b) assert((a == 1), "The first parameter must be equal to 1") print(b) return a+1 end
How to do it…
Here's how you can catch a nonfatal error with pcall
by emulating the try
and catch
block:
function try(fn, catch_fn) local status, msg = pcall(fn) if not status then catch_fn(msg) end end try(function() f1(2, 3) -- this will throw "an exception" end, function(e) print('An exception occured:', e) error('Throw exception') end)
The next recipe shows how to create your own specialized xpcall2
function that can handle input parameters for a function:
local function xpcall2(fn, ...) local arg = {...} return xpcall( -- function wrapper to pass function arguments function(...) return fn(unpack(arg)) end, -- error function function(msg) return debug.traceback(msg, 3) end ) end print(xpcall2(f1, 2, 'a'))
How it works…
The whole principle of the try
and catch
block emulation in Lua relies on the pcall
function that catches the error message and pushes it into the catch
block function.
The only weakness of this approach is that you can't get more information because you're handling errors outside of the scope of where the error occurred.
This issue can be solved with xpcall
which handles error before stack unwinding so you can use the debug library to get more information about the error.
Xpcall2
works as a wrapper function that not only passes parameters into protected function calls, but also handles getting the trace back with the debug.traceback
function and returns results or a status code with an error message.