且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否应该捕获boost :: asio :: io_service :: run()引发的异常?

更新时间:2023-11-12 17:30:28

是。

据记录,传播从完成处理程序引发的异常。因此,您需要根据您的应用程序来处理它们。

It is documented that exceptions thrown from completion handlers are propagated. So you need to handle them as appropriate for your application.

在很多情况下,这将循环并重复 run(),直到没有错误退出为止。

In many cases, this would be looping and repeating the run() until it exits without an error.

在我们的代码库中,我有类似的东西

In our code base I have something like

static void m_asio_event_loop(boost::asio::io_service& svc, std::string name) {
    // http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers
    for (;;) {
        try {
            svc.run();
            break; // exited normally
        } catch (std::exception const &e) {
            logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running " << name << " task: " << e.what();
        } catch (...) {
            logger.log(LOG_ERR) << "[eventloop] An unexpected error occurred running " << name << " task";
        }
    }
}

以下是文档链接 http:// www .boost.org / doc / libs / 1_61_0 / doc / html / boost_asio / reference / io_service.html#boost_asio.reference.io_service.effect_of_exceptions_thrown_from_handlers