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

标签 c++ c++11 exception

我有这个抛出异常的代码(非常类似于 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().

关于c++ - 如何将通用错误代码枚举与来自 <system_error> 的 system_category 错误代码一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46370615/

相关文章:

C++ : Catch a divide by zero error

c++ - 有没有办法使 unique_ptr 的实例化不那么冗长?

c++ - 另一个小部件 Qt 中的小部件

c++ - 如何获取 lambda 的返回类型,C++11 中的 reduce 函数

cocoa - NSFetchedResultsController 缓存再次不匹配

c++ - vector 删除范围内的元素

c++ - 通用/模板编程最佳实践 : To limit types, 或不限制类型

c++ - 何时以及如何使用 std::locale::messages?

C# Neo4jClient TaskCancelled 异常

c# - 来自另一个方法的意外返回值的异常