Reputation: 15
std::string Window::Exception::TranslateErrorCode(HRESULT hr) noexcept
{
char* pMsgBuf = nullptr;
DWORD nMsgLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&pMsgBuf),
0,
nullptr
);
if (nMsgLen == 0)
{
return "Unidentified error code";
}
std::string errorString = pMsgBuf;
LocalFree(pMsgBuf);
return errorString;
}
This is the code that returns the description string, however the string on the description is only 1 letter long, i think that the problem is that pMsgBuf that is a LPWSTR, but i don't know how to setup reinterpret_cast with LPSTR, cause if i put LPSTR it gives me an error: "Argument of type 'LPSTR' is incompatible with parameter of type 'LPWSTR'"
Upvotes: 0
Views: 82
Reputation: 1587
First, it's 2024 and using ANSI strings in modern applications is inexcusable. You should set your project to UNICODE and use wide strings.
std::wstring Window::Exception::TranslateErrorCode(HRESULT hr) noexcept
{
LPWSTR pBuffer = nullptr;
DWORD Result = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&pBuffer),
0,
nullptr);
if (Result == 0) {
return L"Unidentified error code";
}
std::wstring ErrorString = pBuffer;
LocalFree(pBuffer);
return ErrorString;
}
Second, you are passing a HRESULT
into this code. While you can get an error message text from that you need to be aware that not all HRESULT
codes come from FACILITY_WIN32
and that the error message you get back can be completely wrong.
Upvotes: 1