After a Windows API call, how can I get the last error message in a textual form?
GetLastError()
returns an integer value, not a text message.
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string(); //No error message has been recorded
}
LPSTR messageBuffer = nullptr;
//Ask Win32 to give us the string version of that message ID.
//The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
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);
//Copy the error message into a std::string.
std::string message(messageBuffer, size);
//Free the Win32's string's buffer.
LocalFree(messageBuffer);
return message;
}
(LPSTR)&messageBuffer
in this case, as otherwise there's no way FormatMessageA could alter its value to point to the allocated buffer.
1
GetLastError
is potentially called too late. 2
No Unicode support. 3
Use of exceptions without implementing exception safety guarantees.
Aug 8, 2017 at 10:20
FormatMessage()
, as described on this MSDN page.
Updated (11/2017) to take into consideration some comments.
Easy example:
wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, (sizeof(buf) / sizeof(wchar_t)), NULL);
1
Failure to specify the important FORMAT_MESSAGE_IGNORE_INSERTS
flag. 2
GetLastError
potentially called too late. 3
Arbitrary restriction of the message to 256 code units. 4
No error handling.
Aug 8, 2017 at 10:22
256
instead of (sizeof(buf) / sizeof(wchar_t)
? does it acceptable and safe?
Aug 5, 2018 at 4:39
Since c++11, you can use the standard library instead of FormatMessage
:
#include <system_error>
if (!SomeWin32Function()){
DWORD error = ::GetLastError();
std::string message = std::system_category().message(error);
...
}
GetLastError
produces a meaningful result. With this being C++, the only safe option here is to have the caller provide the last error code. It certainly doesn't help, that the code presented calls GetLastError
twice. Also, while convenient, C++' inherent lack of wide character support fails to make the error_category
interface universally useful. This just adds to C++' long history of missed opportunities.
May 29, 2020 at 6:50
GetLastError
. But I see not difference between calling GetLastError
here or having the caller call it. Regarding C++ and wchar: Don't abandon hope, Microsoft is starting to allow apps to be UTF-8 only.
log_error("error", GetLastErrorAsString());
. Also consider that log_error
's first argument is of type std::string
. The (invisible) conversion c'tor call just dropped your guarantees to capture a meaningful value from GetLastError
at the point you are calling it.
May 29, 2020 at 7:15
malloc
calls HeapAlloc
for the process heap. The process heap is growable. If it needs to grow, it will ultimately call VirtualAlloc, which does set the calling thread's last error code. Now that's totally missing the point, which is: C++ is a minefield. This implementation just adds to that, by providing an interface with implied guarantees it simply cannot live up to. If you believe that there is no problem, it should be easy for you to prove the proposed solution's correctness. Good luck.
May 29, 2020 at 11:05
MSDN has some sample code that demonstrates how to use FormatMessage()
and GetLastError()
together: Retrieving the Last-Error Code
GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:
// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
//
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
if (cchBufferLength == 0)
{
return FALSE;
}
DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
pBuffer,
cchBufferLength,
NULL);
return (cchMsg > 0);
}
In C++, you can simplify the interface considerably by using the std::string class:
#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;
String GetErrorMessage(DWORD dwErrorCode)
{
LPTSTR psz{ nullptr };
const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
dwErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&psz),
0,
NULL);
if (cchMsg > 0)
{
// Assign buffer to smart pointer with custom deleter so that memory gets released
// in case String's c'tor throws an exception.
auto deleter = [](void* p) { ::LocalFree(p); };
std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
return String(ptrBuffer.get(), cchMsg);
}
else
{
auto error_code{ ::GetLastError() };
throw std::system_error( error_code, std::system_category(),
"Failed to retrieve error message string.");
}
}
NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.
FORMAT_MESSAGE_IGNORE_INSERTS
flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.This answer has been incorporated from Stack Overflow Documentation. The following users have contributed to the example: stackptr, Ajay, Cody Gray♦, IInspectable.
std::runtime_error
, I suggest to throw std::system_error(lastError, std::system_category(), "Failed to retrieve error message string.")
where lastError
would be the return value of GetLastError()
after the failed FormatMessage()
call.
FormatMessage
directly?
Mar 14, 2019 at 15:43
::HeapFree(::GetProcessHeap(), 0, p)
in the deleter instead of ::LocalFree(p)
as the documentation suggests? 2) I realize that the documentation says to do it this way, but doesn't reinterpret_cast<LPTSTR>(&psz)
violate the strict aliasing rule?
HeapFree
was introduced, while this was still a topic in SO Documentation. I'll have to investigate (although the documentation seems to be clear, that this is not safe). Question 2): This is two-fold. For an MBCS configuration, LPTSTR
is an alias for char*
. That cast is always safe. For a Unicode configuration, casting to wchar_t*
is fishy at any rate. I don't know if this is safe in C, but it's most likely not in C++. I'd have to investigate this, too.
Aug 4, 2019 at 21:15
In general, you need to use FormatMessage
to convert from a Win32 error code to text.
From the MSDN documentation:
Formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.
The declaration of FormatMessage:
DWORD WINAPI FormatMessage(
__in DWORD dwFlags,
__in_opt LPCVOID lpSource,
__in DWORD dwMessageId, // your error code
__in DWORD dwLanguageId,
__out LPTSTR lpBuffer,
__in DWORD nSize,
__in_opt va_list *Arguments
);
If you're using c# you can use this code:
using System.Runtime.InteropServices;
public static class WinErrors
{
#region definitions
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
static extern int FormatMessage(FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr Arguments);
[Flags]
private enum FormatMessageFlags : uint
{
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
FORMAT_MESSAGE_FROM_STRING = 0x00000400,
}
#endregion
/// <summary>
/// Gets a user friendly string message for a system error code
/// </summary>
/// <param name="errorCode">System error code</param>
/// <returns>Error string</returns>
public static string GetSystemMessage(int errorCode)
{
try
{
IntPtr lpMsgBuf = IntPtr.Zero;
int dwChars = FormatMessage(
FormatMessageFlags.FORMAT_MESSAGE_ALLOCATE_BUFFER | FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero,
(uint) errorCode,
0, // Default language
ref lpMsgBuf,
0,
IntPtr.Zero);
if (dwChars == 0)
{
// Handle the error.
int le = Marshal.GetLastWin32Error();
return "Unable to get error code string from System - Error " + le.ToString();
}
string sRet = Marshal.PtrToStringAnsi(lpMsgBuf);
// Free the buffer.
lpMsgBuf = LocalFree(lpMsgBuf);
return sRet;
}
catch (Exception e)
{
return "Unable to get error code string from System -> " + e.ToString();
}
}
}
If you need to support MBCS as well as Unicode, Mr.C64's answer is not quite enough. The buffer must be declared TCHAR, and cast to LPTSTR. Note that this code doesn't deal with the annoying newline that Microsoft appends to the error message.
CString FormatErrorMessage(DWORD ErrorCode)
{
TCHAR *pMsgBuf = NULL;
DWORD nMsgLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&pMsgBuf), 0, NULL);
if (!nMsgLen)
return _T("FormatMessage fail");
CString sMsg(pMsgBuf, nMsgLen);
LocalFree(pMsgBuf);
return sMsg;
}
Also, for brevity I find the following method useful:
CString GetLastErrorString()
{
return FormatErrorMessage(GetLastError());
}
CString
c'tor throws an exception, this implementation leaks the memory allocated by the call to FormatMessage
.
Aug 8, 2017 at 10:27
void WinErrorCodeToString(DWORD ErrorCode, string& Message)
{
char* locbuffer = NULL;
DWORD count = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, ErrorCode,
0, (LPSTR)&locbuffer, 0, nullptr);
if (locbuffer)
{
if (count)
{
int c;
int back = 0;
//
// strip any trailing "\r\n"s and replace by a single "\n"
//
while (((c = *CharPrevA(locbuffer, locbuffer + count)) == '\r') ||
(c == '\n')) {
count--;
back++;
}
if (back) {
locbuffer[count++] = '\n';
locbuffer[count] = '\0';
}
Message = "Error: ";
Message += locbuffer;
}
LocalFree(locbuffer);
}
else
{
Message = "Unknown error code: " + to_string(ErrorCode);
}
}
1
No Unicode support. 2
Inappropriate formatting of the error message. If the caller needs to process the returned string, it can just do so. Your implementation leaves the caller with no option. 3
Use of exceptions but lack of proper exception safety. In case the std::string
operators throw exceptions, the buffer allocated by FormatMessage
is leaked. 4
Why not simply return a std::string
instead of having the caller pass an object by reference?
Aug 8, 2017 at 10:32
Here is my minimal C++ example using std::string/wstring.
#include <windows.h>
#include <string>
typedef std::basic_string<TCHAR> String;
String errorMessage(DWORD dwError)
{
LPTSTR lpBuffer = NULL;
String ret = TEXT("");
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, 0, (LPTSTR)&lpBuffer, 0, NULL))
ret = String(lpBuffer);
LocalFree(lpBuffer);
return ret;
}
It doesn't have any error checking though and just returns an empty string if it can't find the specified error. You can implement your own error checking if you like.
Why waste time write lot code, when few code do trick?
I pass 0 for dwLanguageId as it's the right way to do it, as other answers failed to notice that MAKELANGID macro is deprecated and should not be used as it is inconsistent and doesn't work at all for some languages.
Here is an excerpt from winnt.h in Windows SDK 10.0.19041.0 (2020-05-12) stating the issue:
//
// ** DEPRECATED ** DEPRECATED ** DEPRECATED ** DEPRECATED ** DEPRECATED **
//
// DEPRECATED: The LCID/LANGID/SORTID concept is deprecated, please use
// Locale Names instead, eg: "en-US" instead of an LCID like 0x0409.
// See the documentation for GetLocaleInfoEx.
//
// A language ID is a 16 bit value which is the combination of a
// primary language ID and a secondary language ID. The bits are
// allocated as follows:
//
// +-----------------------+-------------------------+
// | Sublanguage ID | Primary Language ID |
// +-----------------------+-------------------------+
// 15 10 9 0 bit
//
// WARNING: This pattern is broken and not followed for all languages.
// Serbian, Bosnian & Croatian are a few examples.
//
// WARNING: There are > 6000 human languages. The PRIMARYLANGID construct
// cannot support all languages your application may encounter.
// Please use Language Names, such as "en".
//
// WARNING: There are > 200 country-regions. The SUBLANGID construct cannot
// represent all valid dialects of languages such as English.
// Please use Locale Names, such as "en-US".
//
// WARNING: Some languages may have more than one PRIMARYLANGID. Please
// use Locale Names, such as "en-FJ".
//
// WARNING: Some languages do not have assigned LANGIDs. Please use
// Locale Names, such as "tlh-Piqd".
//
// It is recommended that applications test for locale names rather than
// attempting to construct/deconstruct LANGID/PRIMARYLANGID/SUBLANGID
//
// Language ID creation/extraction macros:
//
// MAKELANGID - construct language id from a primary language id and
// a sublanguage id.
// PRIMARYLANGID - extract primary language id from a language id.
// SUBLANGID - extract sublanguage id from a language id.
//
// Note that the LANG, SUBLANG construction is not always consistent.
// The named locale APIs (eg GetLocaleInfoEx) are recommended.
//
// DEPRECATED: Language IDs do not exist for all locales
//
// ** DEPRECATED ** DEPRECATED ** DEPRECATED ** DEPRECATED ** DEPRECATED **
//
Seems just that the information hasn't made its' way to the official MSDN doc of MAKELANGID yet.
Even if it did work correctly, it's the worse option since it tries to find the error string on that specified LangID and only that one ID, failing if it doesn't exist. Using 0 instead will very likely return at least something, even if that error isn't localized to the user's language.
Quote from MSDN FormatMessageW:
[in] dwLanguageId
The language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
If you pass a specific LANGID in this parameter, FormatMessage will return a message for that LANGID only. If the function cannot find a message for that LANGID, it sets Last-Error to ERROR_RESOURCE_LANG_NOT_FOUND. If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order:
- Language neutral
- Thread LANGID, based on the thread's locale value
- User default LANGID, based on the user's default locale value
- System default LANGID, based on the system default locale value
- US English
If FormatMessage does not locate a message for any of the preceding LANGIDs, it returns any language message string that is present. If that fails, it returns ERROR_RESOURCE_LANG_NOT_FOUND.
String
c'tor throws an exception. It also needlessly calculates the string length after knowing the length already. Compare to this implementation that addresses both issues.
May 13, 2022 at 21:48
const
value does more harm than good (if any). You have just disabled the compiler's ability to move from this value, forcing clients to make unnecessary copies. Honestly, the more I look at this the more I feel like this is actually down-vote material. Sorry.
May 14, 2022 at 10:31
@err,hr
watch, and have the debugger automatically convert the last error code to a human-readable representation. The,hr
format specifier works for any expression that evaluates to an integral value, e.g. a5,hr
watch will display "ERROR_ACCESS_DENIED : Access is denied.".GetLastError()
documentation: "To obtain an error string for system error codes, use theFormatMessage()
function.". See the Retrieving the Last-Error Code example on MSDN.