From 9d0a9d4e23f022bc3fb0f3d6bf98bd401674be4c Mon Sep 17 00:00:00 2001 From: yhirose Date: Sun, 27 Nov 2022 10:05:30 -0500 Subject: [PATCH] Fix #1437 --- httplib.h | 11 ++++++++++- test/test.cc | 27 ++++++++++++++++++++------- 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/httplib.h b/httplib.h index e96b561..ff11e36 100644 --- a/httplib.h +++ b/httplib.h @@ -5855,7 +5855,16 @@ Server::process_request(Stream &strm, bool close_connection, routed = true; } else { res.status = 500; - res.set_header("EXCEPTION_WHAT", e.what()); + std::string val; + auto s = e.what(); + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case '\r': val += "\\r"; break; + case '\n': val += "\\n"; break; + default: val += s[i]; break; + } + } + res.set_header("EXCEPTION_WHAT", val); } } catch (...) { if (exception_handler_) { diff --git a/test/test.cc b/test/test.cc index a92d0a5..9e66561 100644 --- a/test/test.cc +++ b/test/test.cc @@ -3839,9 +3839,12 @@ TEST(MountTest, Unmount) { TEST(ExceptionTest, ThrowExceptionInHandler) { Server svr; - svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) { + svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) { throw std::runtime_error("exception..."); - // res.set_content("Hello World!", "text/plain"); + }); + + svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) { + throw std::runtime_error("exception\r\n..."); }); auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); }); @@ -3854,11 +3857,21 @@ TEST(ExceptionTest, ThrowExceptionInHandler) { Client cli("localhost", PORT); - auto res = cli.Get("/hi"); - ASSERT_TRUE(res); - EXPECT_EQ(500, res->status); - ASSERT_TRUE(res->has_header("EXCEPTION_WHAT")); - EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT")); + { + auto res = cli.Get("/exception"); + ASSERT_TRUE(res); + EXPECT_EQ(500, res->status); + ASSERT_TRUE(res->has_header("EXCEPTION_WHAT")); + EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT")); + } + + { + auto res = cli.Get("/unknown"); + ASSERT_TRUE(res); + EXPECT_EQ(500, res->status); + ASSERT_TRUE(res->has_header("EXCEPTION_WHAT")); + EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT")); + } svr.stop(); listen_thread.join();