In my application, we're trying to remove boost features and replace with C++ Standard Library features. Here I've a boost::system::error_code prepared from GetLastError and thrown from one place. And handled in another place by preparing error string.
void fun()
{
boost::system::error_code ec(GetLastError(), boost::system::system_category());
throw ec;
}
int main()
{
try
{
fun();
}
catch ( boost::system::error_code ec )
{
if (ec == boost::asio::error::operation_aborted)
string strError(ec.message();
}
}
I found that I can replace it with std::error_code. But when I try with a sample program, I'm not able to get the same string. I tried all three categories of std::error_code. I need a replacement, which gives exact same string.
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size - 3); // Getting rid of trailing characters: ".\r\n"
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
int _tmain(int argc, _TCHAR* argv[])
{
SetLastError(ERROR_OPERATION_ABORTED);
std::error_code er(GetLastError(), std::generic_category());
cout << "STD Generic Error: " << er.message() << endl;
std::error_code sysEr(GetLastError(), std::system_category());
cout << "STD System Error: " << sysEr.message() << endl;
std::error_code ioEr(GetLastError(), std::iostream_category());
cout << "STD I/O Error: " << ioEr.message() << endl;
cout << "STL Error: " << GetLastErrorAsString() << endl;
boost::system::error_code ec(GetLastError(), boost::system::system_category());
cout << "Boost Error: " << ec.message() << endl;
}
Output:
STD Generic Error: unknown error
STD System Error: operation canceled
STD I/O Error: unknown error
STL Error: The I/O operation has been aborted because of either a thread exit or an application request
Boost Error: The I/O operation has been aborted because of either a thread exit or an application request