I want to serialize an std::error_code, transport it over the network and deserialize it again. Is there anyway to do this or will I need a translation table (switch-case) which maps integer values to/from an std::error_code?

int encode_error(const std::error_code& ec);
std::error_code decode_error(int value);

Thanks.

有帮助吗?

解决方案 2

A std::error_code is a combination of two things:

  1. An integer value (usually mapped from an enum of some sort); and
  2. A pointer to the category that generated them.

To serialize them in the general case is very difficult, as you would need to know all of the possible categories that could be used, and then transmit which category is appropriate along with the value. The receiver would then need to look up the matching category locally and use that to create the error code from that.

A simpler case would be to get the message, category name, and error value, and send that. It would be impractical to translate that back into an error_code, but depending on your use case, it might be sufficient.

If you want to serialize error_codes from a custom category that you control is much simpler, since you eliminate the need to determine which category the error came from, so it should be trivial to serialize that.

其他提示

You need to use std::error_condition, which is a portable error code.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top