如何将通用错误代码枚举与来自 <system_error> 的 system_category 错误代码一起使用?

How do I use the generic error codes enum with system_category error codes from <system_error>?

我有这段代码(与 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)以及某种系统,该系统应该在系统特定错误代码和这些泛型错误之间进行转换。

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

在足够高质量的实现上*,做到

就足够了
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().