2023-08-18 16:25:16 (UTC-03:00)
Marcel Rodrigues <marcelgmr@gmail.com>
run callbacks in coroutine to catch errors
diff --git a/lib/ludweb/app.lua b/lib/ludweb/app.lua index bbc0f60..184276a 100644 --- a/lib/ludweb/app.lua +++ b/lib/ludweb/app.lua @@ -7,7 +7,12 @@ function App:add_route(method, pattern, callback) table.insert(self.routes, {method, pattern, callback}) end -function App:run(port) +function App:is_debug_on() + return self.debug +end + +function App:run(port, debug_mode) + self.debug = debug_mode or false self.server:run(port) end @@ -36,7 +41,21 @@ local function new_app(routes) if req.method == method then local params = {req.path:match("^"..pattern.."$")} if #params > 0 then - return func(req, unpack(params)) + local co = coroutine.create(func) + local vals = {coroutine.resume(co, req, unpack(params))} + local ok = table.remove(vals, 1) + if ok then + return unpack(vals) + else + local msg = "Internal Server Error" + local err_msg = vals[1] + if obj:is_debug_on() then + msg = msg.."<br>"..err_msg + else + io.stderr:write("app error: "..err_msg.."\n") + end + return msg, 500, "Internal Server Error" + end end end end