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'"
First, it's 2024 and using ANSI strings in modern applications is inexcusable. You should set your project to UNICODE and use wide strings.
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 allHRESULT
codes come fromFACILITY_WIN32
and that the error message you get back can be completely wrong.