James
James

Reputation: 9278

Boost ASIO: recovering from handler exceptions

If an ASIO callback throws an error is it safe to resume the async processing?

In short, does the following code have any merit?

void runAsioLoop()
{
    boost::asio::io_service::work work(this->m_ioService);
    boost::system::error_code unused;

    while (m_running) {
        try {
            this->m_ioService.run(unused);
            this->m_ioService.reset();
        } catch (...) {
            std::cerr << "*** An error happened\n";
        }
    }
}

Upvotes: 1

Views: 348

Answers (1)

sehe
sehe

Reputation: 393487

It should work, but the better idiom is:

for (;;) {
    try {
        svc.run();
        break; // exited normally
    } catch (std::exception const &e) {
        logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running a task: " << e.what();
    } catch (...) {
        logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running a task";
    }
}

Here's the documentation for it: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers

Upvotes: 1

Related Questions