lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


jason bright wrote:
> Not to hijack this thread, but can somebody point to any wiki articles or
> otherwise about using error handlers with lua_pcall().  Doing my first
> project with Lua and everything is going swimmingly, but would like some
> more robustness and feedback to the user (e.g. reporting the actual line and
> some context for a syntax error).  How lua_pcall uses it's error handler
> isn't very clear to me from PiL nor the online docs.

I do things in pure Lua mode kind of like this:

function program(args)
	LOGGER = assert( logging.file("program.log") )
	assert( xpcall( function () run(args) end, logerror ) )
end

functions run(args)
	-- some set up
	dofile("program.conf")
end

function logerror(err)
	local cmdline = ''
	for i = 0, arg.n do
		cmdline = cmdline .. '"' ..  arg[i] .. '" '
	end
	local traceback = debug.traceback()
	LOGGER:fatal(cmdline)
	LOGGER:fatal(err)
	LOGGER:debug(traceback)
	return err
end

-- here is a function that can get invoked by the config file like "foo { foo = 42 }"
function foo(t)
	if not t.foo then
		error("You haven't set foo correctly. Check your config file.", 2)
	end
	success, err = pcall(not_my_own_function, t)
	if not success then
		error(err, 2)
	end
end


Any errors that are encountered are reported against the line in the
config file where they got triggered (using the second parameter to
error()).  And any functions I invoke that I am not in control of
(LuaSocket, LuaSQL and the like) are wrapped in the pcall().  This
allows me some reasonable control over the way the error is reported
to the user.

If I am invoking my own functions that are more complicated, to the
point of making it impossible to set the error stack level parameter,
then I also wrap them in pcall() and contruct an error message with
error().

Not necessarily very generic and pretty, but all in all quite elegant
and easy to work with.

Hope this helps,
Robby