I just made a module to have a better way to handle errors in lua.
Why this module ? Because the way lua uses to handle errors is not so
easy to use :
- some errors messages depends of parameters given to the function or
filename and linenumber
- no easy way to catch some errors but not all errors
That's why I created this module.
To use it, place the lua file somewhere on your LUA_PATH and :
ex = require("exception.lua").install()
The install() is required to replace debug.traceback() used to display
non protected errors.
it also register in the global environment 2 functions : try and raise
it also modify the function assert()
Now, how to use it ?
the function raise(error, message [, level ] ) raise an error
identified by error (a string like "file_does_not_exists") and
described by message (a string like "foo: no such file or directory")
The level works exactly like in the error() function
the function try(func, handler) will execute func in protected mode and
in case of error will call handler with the exception (called e) as 1st
You can then test the error using e.error and display some usefun
informations with e.message, e.location and e.traceback
If the error handler returns false or nil the error will be raised
again (without losing the stack traceback).
The result of the try function will be the result of func if no errors
or the result of the handler function (except the first result) in case
the modified assert function take 3 parameters :
assert(boolean, error, message)
it work exactly like the original assert but raises an exception
instead of en error (that is a table with an error name different of
the error message)
Note that this system is compatible with the normal error handling in
lua. an error raised by the error function will be catched by try() ...
but the error identifier and the error message will be the same.
Example of use :
result = try(function()
-- here some code that raises some errors
if e.error == 'error1' then
-- do something to repair the error1
return true, 'ok'
elseif e.error == 'error2' then
print('too bad, the error2 happened')
-- here result == 'ok'
What do you think about that ?
It would be great to have a system like that in the next release of lua
(lua 5.2 ?).