【问题标题】:How do I use the generic error codes enum with system_category error codes from <system_error>?如何将通用错误代码枚举与 <system_error> 中的 system_category 错误代码一起使用?
【发布时间】:2017-09-22 17:55:29
【问题描述】:

我有这个抛出异常的代码(非常类似于what is suggested here):

int accept4(int sockfd, sockaddr *addr, socklen_t *addrlen, int flags)
{
   const int fd = ::accept4(sockfd, addr, addrlen, flags);
   if (fd < 0)
   {
       const auto tmp = errno;
       throw ::std::system_error(tmp, ::std::system_category(), "accept4(2)");
   }
   else
   {
      return fd;
   }
}

以及用于测试特定异常原因的代码:

catch (const ::std::system_error &e)
{
   static const auto block_err = ::std::system_error(EWOULDBLOCK,
                                                     ::std::system_category());

   const auto ecode = e.code(); 

   // EWOULBLOCK is fine, everything else, re-throw it.
   if (block_err.code() != ecode)
   {
      throw;
   }
}

这似乎有点不必要的冗长,也不是正确的做事方式。有一般错误的整个想法和一个完整的枚举(参见::std::errc)以及某种应该在系统特定错误代码和这些一般错误之间转换的系统。

我想使用通用错误代码和类别,但我似乎无法让它们工作。我该怎么做?

【问题讨论】:

    标签: c++ c++11 exception-handling


    【解决方案1】:

    在足够高质量*的实现上,这样做就足够了

    if (e.code() != std::errc::operation_would_block)
        throw;
    

    如果没有,你会被困住

    if (e.code() != std::error_code(EWOULDBLOCK, std::system_category()))
        throw;
    

    当然没有必要仅仅为里面的错误代码构造另一个system_error


    * 需要实现system_category()default_error_condition,将错误正确映射到generic_category()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2014-03-18
      • 2015-04-29
      相关资源
      最近更新 更多