如何使用来自的system_category错误代码的通用错误代码枚举?

问题描述:

我有这样的代码(非常类似于what is suggested here)抛出异常:如何使用来自<system_error>的system_category错误代码的通用错误代码枚举?

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()