不带的
如何使用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);
}
发布于 2009-01-18 17:32:16
下面是从系统获取错误消息的正确方法(本例中名为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;
}
这与David Hanak的答案之间的关键区别在于FORMAT_MESSAGE_IGNORE_INSERTS
标志的使用。MSDN不太清楚应该如何使用插入,但是在检索系统消息时使用Raymond Chen notes that you should never use them,因为您无法知道系统需要哪些插入。
顺便说一句,如果你使用的是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
}
据我所知,它不是MFC或ATL的一部分。
发布于 2009-09-16 22:15:29
请记住,您不能执行以下操作:
{
LPCTSTR errorText = _com_error(hresult).ErrorMessage();
// do something with the error...
//automatic cleanup when error goes out of scope
}
因为类是在堆栈上创建和销毁的,所以让errorText指向无效的位置。在大多数情况下,此位置仍然包含错误字符串,但在编写线程化应用程序时,这种可能性很快就会消失。
所以总是按照上面的Shog9回答的那样做:
{
_com_error error(hresult);
LPCTSTR errorText = error.ErrorMessage();
// do something with the error...
//automatic cleanup when error goes out of scope
}
发布于 2009-01-18 16:57:41
试试这个:
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);
}
https://stackoverflow.com/questions/455434
复制相似问题