如评论中所述,您必须了解可能从远程服务器接收到的错误代码。从远程服务器接收到的
std::string
包含两部分,正如您所说,
问题在于这些由字符串标识,例如“0A01”,还包含一条消息,而错误代码需要一个整数作为值。
由于您没有分享错误消息的格式,因此我不会添加拆分它的代码,请将您的字符串拆分为2个部分,
- 错误代码
- 错误消息
现在您可以使用
std::stoi(error_code)
将类型为
std::string
的错误代码转换为
int
。所以假设
int error_code_int = std::stoi(string_to_hexadecimal(error_code));
针对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));
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.
您可以使用
此帖子中的string_to_hexadecimal()
函数来进行转换。
我希望您现在可以根据自己的需要修改上面的代码。
编辑1:
正如您所说:
这假设动态消息是全局值。我如何将其传递给std::error_category
对象?
您可以看到,std::error_code::assign
和构造函数std::error_code::error_code
都采用int
类型的参数作为错误代码编号和error_category
。因此,显然std::error_code
无法获取动态消息。
但是,请等一下,我说过std::error_code
在构造函数中使用error_category
作为参数,那么我们有没有办法在那里分配动态消息呢?
std::error_category
指出:
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.");
std::error_code
。否则,编写一个具有两个字符串字段的类应该不难。 - freakish