Browse Source

Merge branch 'use_exception_ptr' of https://github.com/kuguma/cpp-httplib into kuguma-use_exception_ptr

yhirose 3 years ago
parent
commit
916b2a8fd3
2 changed files with 18 additions and 6 deletions
  1. 11 4
      httplib.h
  2. 7 2
      test/test.cc

+ 11 - 4
httplib.h

@@ -614,7 +614,7 @@ public:
   using Handler = std::function<void(const Request &, Response &)>;
   using Handler = std::function<void(const Request &, Response &)>;
 
 
   using ExceptionHandler =
   using ExceptionHandler =
-      std::function<void(const Request &, Response &, std::exception &e)>;
+      std::function<void(const Request &, Response &, std::exception_ptr ep)>;
 
 
   enum class HandlerResponse {
   enum class HandlerResponse {
     Handled,
     Handled,
@@ -5721,15 +5721,22 @@ Server::process_request(Stream &strm, bool close_connection,
     routed = routing(req, res, strm);
     routed = routing(req, res, strm);
   } catch (std::exception &e) {
   } catch (std::exception &e) {
     if (exception_handler_) {
     if (exception_handler_) {
-      exception_handler_(req, res, e);
+      auto ep = std::current_exception();
+      exception_handler_(req, res, ep);
       routed = true;
       routed = true;
     } else {
     } else {
       res.status = 500;
       res.status = 500;
       res.set_header("EXCEPTION_WHAT", e.what());
       res.set_header("EXCEPTION_WHAT", e.what());
     }
     }
   } catch (...) {
   } catch (...) {
-    res.status = 500;
-    res.set_header("EXCEPTION_WHAT", "UNKNOWN");
+    if (exception_handler_) {
+      auto ep = std::current_exception();
+      exception_handler_(req, res, ep);
+      routed = true;
+    } else {
+      res.status = 500;
+      res.set_header("EXCEPTION_WHAT", "UNKNOWN");
+    }
   }
   }
 #endif
 #endif
 
 

+ 7 - 2
test/test.cc

@@ -1249,8 +1249,13 @@ TEST(ExceptionHandlerTest, ContentLength) {
   Server svr;
   Server svr;
 
 
   svr.set_exception_handler([](const Request & /*req*/, Response &res,
   svr.set_exception_handler([](const Request & /*req*/, Response &res,
-                               std::exception &e) {
-    EXPECT_EQ("abc", std::string(e.what()));
+                               std::exception_ptr ep) {
+    EXPECT_FALSE(ep == nullptr);
+    try{
+      std::rethrow_exception(ep);
+    }catch(std::exception& e){
+      EXPECT_EQ("abc", std::string(e.what()));
+    }
     res.status = 500;
     res.status = 500;
     res.set_content("abcdefghijklmnopqrstuvwxyz",
     res.set_content("abcdefghijklmnopqrstuvwxyz",
                     "text/html"); // <= Content-Length still 13 at this point
                     "text/html"); // <= Content-Length still 13 at this point