drogon icon indicating copy to clipboard operation
drogon copied to clipboard

Invalid route parameter returns 500 instead of 404

Open Colysia opened this issue 1 year ago • 1 comments

Describe the bug When making a request to the route /api/num/{number} with a parameter like /api/num/s-1.2e-3, the server returns a 500 Internal Server Error instead of the expected 404 Not Found. The URL /api/num/s-1.2e-3 should not match the route /api/num/ since it starts with s and is not a valid double. However, the server currently throws a 500 Internal Server Error. And here is the log:

20241201 04:41:45.637000 UTC 37404 ERROR Unhandled exception in /api/num/s-1.2e-3, what(): invalid stod argument - HttpAppFrameworkImpl.cc:124

To Reproduce Steps to reproduce the behavior:

  1. Set up a Drogon server with the following handler registration:
#pragma comment(lib, "Crypt32")
#pragma comment(lib, "Rpcrt4")

#include <drogon/drogon.h>
#include <string>

int main(int argc, char *argv[])
{
  auto &app = drogon::app();

  app.registerHandler("/api/num/{number}",
      [](const drogon::HttpRequestPtr &, std::function<void(const drogon::HttpResponsePtr &)> &&callback, double number) {
        auto resp = drogon::HttpResponse::newHttpResponse();
        std::string text = std::to_string(number);
        resp->setBody(text);
        resp->setContentTypeCode(drogon::CT_TEXT_PLAIN);
        resp->setStatusCode(drogon::k200OK);
        callback(resp);
      },
      {drogon::Get});

  app.setLogLevel(trantor::Logger::kInfo)
      .setLogPath("./")
      .addListener("0.0.0.0", 18080)
      .addListener("::0", 18080)
      .setThreadNum(6)
      .setIdleConnectionTimeout(std::chrono::seconds(5))
      .run();

  return 0;
}

Expected behavior I expected the server to return a 404 Not Found error, as the parameter s-1.2e-3 is not a valid double (it starts with s and cannot be parsed as a number). The server should not attempt to match the route when the parameter is invalid.

Screenshots 捕获

Desktop (please complete the following information):

  • OS: Windows 11
  • Compiler: Visual Studio 2022
  • C++ Standard: C++17
  • Drogon version: 1.9.6
  • Charset: Unicode

Additional context

Colysia avatar Dec 01 '24 05:12 Colysia

You could try to use the ADD_METHOD_VIA_REGEX mecro or the registerMethodViaRegex method, and create a regular expression for matching floating point numbers for your scenario.

an-tao avatar Dec 03 '24 14:12 an-tao