Reputation: 4771
I'm trying to run a series of tests and collect some meta data on each test. If there is an error during one of the tests, I would like to save the back trace information but not to exit the script. For example:
-- Example program
for _, v in ipairs(tests) do
--check some results of function calls
if v == nil then
--error("function X failed") no exit
--save back trace to variable/file
-- continue with program
end
end
I'm not currently aware if it is possible in lua to tell the function error() not to stop after creating the back trace. Any thoughts on how to do this?
Upvotes: 1
Views: 83
Reputation: 7064
debug.traceback ([thread,] [message [, level]])
(source) is what you're looking for. You can write a function that 1. gets a traceback 2. opens a file 3. writes the traceback to the file 4. closes the file.
In that case you'd have to use a level of 2, since 0 would be the debug.traceback
function, 1 would be the function calling it (i.e. your function) and 2 the funcion calling that one. message
could be your error code. Then you just override the error
function locally in your script and you're done; calling error
will just log the error and not exit the program.
EDIT: You can also override error
globally, if you want, but that might lead to unexpected results if something goes terribly wrong somewhere else (code that you didn't write yourself) and the program continues nonetheless.
You'd be better off with a construct like this:
if os.getenv 'DEBUG' then
my_error = function()
-- what I explained above
end
else
my_error = error
end
and just use my_error
in all the places where you'd usually use error
.
Upvotes: 3