Skip to content

Commit

Permalink
Add error_handler to asio_server (#1602)
Browse files Browse the repository at this point in the history
* Add error_handler to asio_server

* Update glaze_asio.hpp
  • Loading branch information
stephenberry authored Feb 7, 2025
1 parent 1dfdede commit 29e92b8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
12 changes: 11 additions & 1 deletion include/glaze/ext/glaze_asio.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,11 @@ namespace glz
{
uint16_t port{};
uint32_t concurrency{1}; // How many threads to use (a call to .run() is inclusive on the main thread)

// Register a callback that takes a string error message on server/registry errors.
// Note that we use a std::string to support a wide source of errors and use e.what()
// IMPORTANT: The code within the callback must be thread safe, as multiple threads could call this simultaneously.
std::function<void(const std::string&)> error_handler{};

~asio_server() { stop(); }

Expand Down Expand Up @@ -485,7 +490,12 @@ namespace glz
}
}
catch (const std::exception& e) {
std::fprintf(stderr, "%s\n", e.what());
if (error_handler) {
error_handler(e.what());
}
else {
std::fprintf(stderr, "glz::asio_server error: %s\n", e.what());
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions tests/asio_repe/asio_repe.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,37 @@ void async_server_test()
expect(result == 200);
}

struct error_api
{
std::function<int()> func = []() {
throw std::runtime_error("func error");
return 0;
};
};

void server_error_test()
{
static constexpr int16_t port = 8765;

glz::asio_server<> server{.port = port, .concurrency = 1};
server.error_handler = [](const std::string& error) {
expect(error == "func error");
};

error_api api{};
server.on(api);

server.run_async();

glz::asio_client<> client{"localhost", std::to_string(port)};
(void)client.init();

int result{};
glz::repe::message msg{};
client.call({"/func"}, msg, 100);
expect(bool(glz::repe::decode_message(result, msg)));
}

int main()
{
notify_test();
Expand All @@ -340,6 +371,7 @@ int main()
async_calls();
raw_json_tests();
async_server_test();
server_error_test();

return 0;
}

0 comments on commit 29e92b8

Please sign in to comment.