|
function try(func)
local catchers = {}
local finalizers = {}
return {
catch = function(self, handle)
catchers[#catchers+1] = handle
return self
end,
finally = function(self, handle)
finalizers[#finalizers+1] = handle
return self
end,
run = function(self)
local ok, err = pcall(func)
if not ok then
for n=1,#catchers do
ok, err = pcall(catchers[n], err)
if not ok then break end
end
end
for n=1,#finalizers do
local ok,2 err2 = pcall(finalizers[n])
if ok then
ok = ok2
err = err2
end
end
if not ok then error(err, 0) end
end
}
end
---------------
function genlog(s)
print(s)
error(s)
end
try(genlog "A")
:catch(genlog "B")
:catch(genlog "C")
:finally(genlog "D")
:finally(genlog "E")
:run()
Prints:
A
B
D
E
D -- To stderr
But in the end it is just a design decision.