简体   繁体   English

Boost.Asio中的异常处理

[英]Exception handling in Boost.Asio

Boost.Asio documentation suggests the following exception handling pattern : Boost.Asio文档建议以下异常处理模式

boost::asio::io_service io_service;
...
for (;;)
{
  try
  {
    io_service.run();
    break; // run() exited normally
  }
  catch (my_exception& e)
  {
    // Deal with exception as appropriate.
  }
}

The problem with it is that the context of exception is lost at the point when it's handled. 它的问题是异常的上下文在处理时丢失了。 For example, if I have multiple socket sessions in a given io_service, I don't know which one caused the exception. 例如,如果我在给定的io_service中有多个套接字会话,我不知道哪个引发了异常。

What would be a better way to handle the exceptions from asynchronous handlers without wrapping them in try/catch blocks? 如果没有将它们包装在try/catch块中,处理异步处理程序的异常会有什么更好的方法?

There is nothing wrong with the pattern recommended by Boost.Asio. Boost.Asio推荐的模式没有任何问题。 What you should do is package any necessary information for handling the exception along with the exception object. 您应该做的是打包处理异常的任何必要信息以及异常对象。 If you use boost::exception (or a type derived from it) for your exception handling, you can very easily attach metadata (including session information) by creating a specialization of boost::error_info and attaching it to the exception object using operator<<. 如果你使用boost :: exception (或从它派生的类型)进行异常处理,你可以通过创建boost :: error_info的特化并使用operator <将它附加到异常对象,非常容易地附加元数据(包括会话信息)。 <。 Your catch block can then extract this info with get_error_info . 然后,您的catch块可以使用get_error_info提取此信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM