我应该如何在C++中正确使用FormatMessage()?

Aar*_*ron 84 c++ windows error-handling formatmessage

没有:

  • MFC
  • ATL

如何使用FormatMessage()获取错误文本HRESULT

 HRESULT hresult = application.CreateInstance("Excel.Application");

 if (FAILED(hresult))
 {
     // what should i put here to obtain a human-readable
     // description of the error?
     exit (hresult);
 }
Run Code Online (Sandbox Code Playgroud)

Sho*_*og9 128

这是从系统中获取错误消息的正确方法HRESULT(在这种情况下命名为hresult,或者您可以替换它GetLastError()):

LPTSTR errorText = NULL;

FormatMessage(
   // use system message tables to retrieve error text
   FORMAT_MESSAGE_FROM_SYSTEM
   // allocate buffer on local heap for error text
   |FORMAT_MESSAGE_ALLOCATE_BUFFER
   // Important! will fail otherwise, since we're not 
   // (and CANNOT) pass insertion parameters
   |FORMAT_MESSAGE_IGNORE_INSERTS,  
   NULL,    // unused with FORMAT_MESSAGE_FROM_SYSTEM
   hresult,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR)&errorText,  // output 
   0, // minimum size for output buffer
   NULL);   // arguments - see note 

if ( NULL != errorText )
{
   // ... do something with the string `errorText` - log it, display it to the user, etc.

   // release memory allocated by FormatMessage()
   LocalFree(errorText);
   errorText = NULL;
}
Run Code Online (Sandbox Code Playgroud)

这与David Hanak的答案之间的关键区别在于使用FORMAT_MESSAGE_IGNORE_INSERTS旗帜.MSDN对如何使用插入有点不清楚,但是Raymond Chen指出在检索系统消息时不应该使用它们,因为你无法知道系统期望的插入.

FWIW,如果您使用的是Visual C++,那么使用_com_error该类可以让您的生活更轻松:

{
   _com_error error(hresult);
   LPCTSTR errorText = error.ErrorMessage();

   // do something with the error...

   //automatic cleanup when error goes out of scope
}
Run Code Online (Sandbox Code Playgroud)

据我所知,直接不是MFC或ATL的一部分.

  • 注意:此代码使用hResult代替Win32错误代码:这些是不同的东西!您可能会得到与实际发生的错误完全不同的错误的文本. (6认同)
  • MSDN 实际上现在提供 [他们的版本](https://docs.microsoft.com/en-us/windows/desktop/debug/retrieving-the-last-error-code) 有点相同的代码。 (2认同)

Mar*_*ius 14

请记住,您无法执行以下操作:

{
   LPCTSTR errorText = _com_error(hresult).ErrorMessage();

   // do something with the error...

   //automatic cleanup when error goes out of scope
}
Run Code Online (Sandbox Code Playgroud)

在堆栈上创建和销毁类时,会将errorText指向无效位置.在大多数情况下,此位置仍将包含错误字符串,但在编写线程应用程序时,这种可能性很快就会消失.

所以总是按照上面Shog9的回答如下:

{
   _com_error error(hresult);
   LPCTSTR errorText = error.ErrorMessage();

   // do something with the error...

   //automatic cleanup when error goes out of scope
}
Run Code Online (Sandbox Code Playgroud)

  • `_com_error`对象是在*示例中的堆栈中创建的.你正在寻找的术语是*临时*.在前一个示例中,对象是在语句末尾被销毁的临时对象. (7认同)
  • 顺便说一句,_com_error在'comdef.h'中声明 (5认同)

Dav*_*nak 12

试试这个:

void PrintLastError (const char *msg /* = "Error occurred" */) {
        DWORD errCode = GetLastError();
        char *err;
        if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                           NULL,
                           errCode,
                           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language
                           (LPTSTR) &err,
                           0,
                           NULL))
            return;

        static char buffer[1024];
        _snprintf(buffer, sizeof(buffer), "ERROR: %s: %s\n", msg, err);
        OutputDebugString(buffer); // or otherwise log it
        LocalFree(err);
}
Run Code Online (Sandbox Code Playgroud)

  • GetLastError不返回HResult.它返回Win32错误代码.可能更喜欢名称PrintLastError,因为这实际上不会*处理*任何东西.并确保使用FORMAT_MESSAGE_IGNORE_INSERTS. (4认同)

Chr*_*ial 6

从 c++11 开始,您可以使用标准库而不是FormatMessage

#include <system_error>

std::string message = std::system_category().message(hr)
Run Code Online (Sandbox Code Playgroud)


Cla*_*ton 5

这更像是对大多数答案的补充,但不是LocalFree(errorText)使用HeapFree函数:

::HeapFree(::GetProcessHeap(), NULL, errorText);
Run Code Online (Sandbox Code Playgroud)

从 MSDN 站点

Windows 10
LocalFree 不在现代 SDK 中,因此它不能用于释放结果缓冲区。相反,使用 HeapFree(GetProcessHeap()、locatedMessage)。在这种情况下,这与在内存上调用 LocalFree 相同。

更新
我发现它LocalFree在 SDK 的 10.0.10240.0 版中(WinBase.h 中的第 1108 行)。但是,警告仍然存在于上面的链接中。

#pragma region Desktop Family or OneCore Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)

WINBASEAPI
_Success_(return==0)
_Ret_maybenull_
HLOCAL
WINAPI
LocalFree(
    _Frees_ptr_opt_ HLOCAL hMem
    );

#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM) */
#pragma endregion
Run Code Online (Sandbox Code Playgroud)

更新 2
我还建议使用该FORMAT_MESSAGE_MAX_WIDTH_MASK标志来整理系统消息中的换行符。

从 MSDN 站点

FORMAT_MESSAGE_MAX_WIDTH_MASK
该函数忽略消息定义文本中的常规换行符。该函数将消息定义文本中的硬编码换行符存储到输出缓冲区中。该函数不会产生新的换行符。

更新 3
似乎有 2 个特定的系统错误代码不会使用推荐的方法返回完整消息:

为什么 FormatMessage 只为 ERROR_SYSTEM_PROCESS_TERMINATED 和 ERROR_UNHANDLED_EXCEPTION 系统错误创建部分消息?