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