fix: Use QString for Windows error functions

Was returning only first char of error message (mild-mojibake)
This commit is contained in:
Nick Bolton
2025-09-12 12:31:12 +01:00
parent 7a2591a1fa
commit 5ea8d0326a
2 changed files with 35 additions and 15 deletions

View File

@ -7,24 +7,30 @@
*/
#include "arch/win32/XArchWindows.h"
#include "base/String.h"
std::string windowsErrorToString(DWORD error)
#include <QString>
QString windowsErrorToQString(DWORD error)
{
char *cmsg;
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 0, error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&cmsg, 0, nullptr
) == 0) {
cmsg = nullptr;
return deskflow::string::sprintf("Unknown error, code %d", error);
LPWSTR buffer = nullptr; // Using FORMAT_MESSAGE_ALLOCATE_BUFFER
DWORD size = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&buffer), 0, nullptr
);
if (size == 0) {
return QString("Unknown Windows error: %1").arg(error);
}
std::string smsg(cmsg);
LocalFree(cmsg);
return smsg;
QString message = QString::fromWCharArray(buffer, int(size));
// Gotcha: Was allocated by FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER)
LocalFree(buffer);
return QString("[%1] %2").arg(error).arg(message.trimmed());
}
std::string winsockErrorToString(int error)
QString winsockErrorToQString(int error)
{
// built-in windows function for looking up error message strings
// may not look up network error messages correctly. we'll have
@ -197,8 +203,19 @@ std::string winsockErrorToString(int error)
for (unsigned int i = 0; s_netErrorCodes[i].m_code != 0; ++i) {
if (s_netErrorCodes[i].m_code == error) {
return s_netErrorCodes[i].m_msg;
return QString("[%1] %2").arg(error).arg(s_netErrorCodes[i].m_msg);
}
}
return "Unknown error";
return QString("Unknown Winsock error: %1").arg(error);
}
std::string windowsErrorToString(DWORD error)
{
return windowsErrorToQString(error).toStdString();
}
std::string winsockErrorToString(int error)
{
return winsockErrorToQString(error).toStdString();
}

View File

@ -8,10 +8,13 @@
#pragma once
#include <QString>
#include <string>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
QString winsockErrorToQString(int error);
QString windowsErrorToQString(DWORD error);
std::string winsockErrorToString(int error);
std::string windowsErrorToString(DWORD error);