From 19ab699fa69764d581c4ae0270092c1957f5cab6 Mon Sep 17 00:00:00 2001 From: blankie Date: Mon, 3 Apr 2023 22:43:40 +0700 Subject: [PATCH] Add exception handler --- main.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/main.cpp b/main.cpp index 08ffc68..26befce 100644 --- a/main.cpp +++ b/main.cpp @@ -26,10 +26,28 @@ int main(int argc, char** argv) { }); server.Get("/style.css", css_route); +#ifndef NDEBUG + server.Get("/debug/exception/known", [](const httplib::Request& req, httplib::Response& res) { + throw std::runtime_error("awoo"); + }); + server.Get("/debug/exception/unknown", [](const httplib::Request& req, httplib::Response& res) { + throw "cope"; + }); +#endif server.Get(".*", [&](const httplib::Request& req, httplib::Response& res) { res.status = 404; serve_error(req, res, config, "404: Page not found"); }); + server.set_exception_handler([&](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) { + res.status = 500; + try { + std::rethrow_exception(ep); + } catch (const std::exception& e) { + serve_error(req, res, config, "500: Internal server error", std::nullopt, e.what()); + } catch (...) { + serve_error(req, res, config, "500: Internal server error", std::nullopt, "Unknown exception"); + } + }); if (config.bind_port != 0) { if (!server.bind_to_port(config.bind_host, config.bind_port)) {