且构网

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

应该捕获 boost::asio::io_service::run() 抛出的异常吗?

更新时间:2023-11-12 18:14:16

是.

据记载,从完成处理程序抛出的异常会被传播.因此,您需要根据您的应用程序适当地处理它们.

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