使用 std::error_code 和非整数值

Using std::error_code with non-integer values

我正在编写一个库,并且希望在远程系统 return 出现错误时 return 错误代码。问题是这些由字符串标识,例如“0A01”,并且还包含一条消息,错误代码需要一个整数作为值。

实现错误代码的最佳方法是什么,它具有 std::error_code 提供的所有功能,但使用字符串作为值?如何将外部错误字符串添加到 std::error_codestd::error_category?

如评论中所述,您必须知道可以从远程服务器接收到的错误代码。 您从远程服务器收到的 std::string 包含您所说的两部分,

The problem is that these are identified by strings, eg, "0A01" and also contain a message, and error code requires an integer as value.

由于您没有分享错误消息的格式,我不会添加吐出它的代码,将您的字符串分成两部分,

  1. 错误代码
  2. 错误信息

现在您可以使用 std::stoi(error_code) 将类型 std::string 的错误代码转换为 int,所以假设

int error_code_int = std::stoi(string_to_hexadecimal(error_code));

对于作为自定义错误消息基础 class 的 std::error_category,请执行此操作,

std::string message_received = "This is the message which received from remote server.";

struct OurCustomErrCategory : std::error_category
{
  const char* name() const noexcept override;
  std::string message(int ev) const override;
};

const char* OurCustomErrCategory::name() const noexcept
{
  return "Error Category Name";
}

std::string OurCustomErrCategory::message(int error_code_int) const
{
    switch (error_code_int)
    {
    case 1:
        return message_received;

    default:
        return "(unrecognized error)";
  }
}

const OurCustomErrCategory ourCustomErrCategoryObject;

std::error_code make_error_code(int e)
{
  return {e, ourCustomErrCategoryObject};
}

int main()
{
    int error_code_int = std::stoi(string_to_hexadecimal(error_code));  // error_code = 0A01
    ourCustomErrCategoryObject.message(error_code_int);
    std::error_code ec(error_code_int , ourCustomErrCategoryObject);
    assert(ec);

    std::cout << ec << std::endl;
    std::cout << ec.message() << std::endl;
}

上述工作示例的输出是

Error Category Name : 0A01
This is the message which received from remote server.

您可以使用 this post 中的函数 string_to_hexadecimal()

希望现在大家可以根据需要修改上面的代码

编辑 1:

如你所说:

This assumes the dynamic message is a global value. How do I pass it to an std::error_category object?

您可以看到 std::error_code::assign and constructor std::error_code::error_code 都采用 int 作为错误代码编号和 error_category 的参数。所以很明显std::error_code不能走动态消息

但是等等,我说过 std::error_code 正在将 error_category 作为构造函数的参数,那么有什么办法,我们可以在那里分配动态消息吗?

std::error_category 表示:

std::error_category serves as the base class for specific error category types.

所以这意味着我们从 std::error_category 派生的 struct 在下面的行

struct OurCustomErrCategory : std::error_category

可以有一个数据成员,我们可以通过成员函数给它赋值,这样我们的struct就会变成这样,

struct OurCustomErrCategory : std::error_category
{
    std::string message_received;
    OurCustomErrCategory(std::string m) : message_received(m) {}

    const char* name() const noexcept override;
    std::string message(int ev) const override;
};

你可以随心所欲地分配它,

const OurCustomErrCategory ourCustomErrCategoryObject("This is the message which received from remote server.");