如何使用来自< system_error>的system_category错误代码的通用错误代码枚举? [英] How do I use the generic error codes enum with system_category error codes from <system_error>?

查看:216
本文介绍了如何使用来自< system_error>的system_category错误代码的通用错误代码枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码(非常类似于这里有什么建议)引发异常:

I have this code (very similar to what is suggested here) that throws an exception:

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;
   }
}

此代码用于测试特定异常原因:

And this code for testing for a particular exception reason:

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 ),以及某些系统,应该在系统特定的错误代码和这些通用错误之间进行转换。

This seems kind of needlessly verbose and not quite the right way to do things. There's this whole idea of generic errors and a whole enum (see ::std::errc) full of them along with some kind of system that's supposed to convert between system specific error codes and these generic errors.

我想使用通用错误代码和类别,我似乎无法让他们工作。如何做这项工作?

I want to use the generic error codes and categories, and I can't seem to get them to work. How do I make that work?

推荐答案

在高质量 * 的实现中,足够了要执行

On an implementation of sufficiently high quality*, it suffices to do

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

如果没有,你被困在

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

当然不需要构建另一个 system_error

There's certainly no need to construct another system_error just for the error code inside.

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

* It needs to implement system_category()'s default_error_condition to appropriately map the error to generic_category().

这篇关于如何使用来自&lt; system_error&gt;的system_category错误代码的通用错误代码枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆