2 /*
3 利用FormatMessage函数得到错误代码的文本显示。而错误代号则可由GetLastError()获得。(_WINDOWS)
4 */
5
6 DWORD nErrorNo = GetLastError ( ); // 得到错误代码
7 LPSTR lpBuffer;
8 FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER |
9 FORMAT_MESSAGE_IGNORE_INSERTS |
10 FORMAT_MESSAGE_FROM_SYSTEM,
11 NULL,
12 nErrorNo, // 此乃错误代码,通常在程序中可由 GetLastError()得之
13 LANG_NEUTRAL,
14 (LPTSTR) & lpBuffer,
15 0 ,
16 NULL );
17 CString strErrorCause = lpBuffer ? _T(lpBuffer) : _T( " Sorry, cannot find this error info. " );
18 UpdateData (FALSE);
19
20 // Free the buffer.
21 LocalFree (lpBuffer);
/*
* MtVerify.h
*
* Error handling for applications in
* "Multitheading Applications in Win32"
*
* The function PrintError() is marked as __inline so that it can be
* included from one or more C or C++ files without multiple definition
* errors. For the examples in this book, this works fine.
* To use the PrintError() in an application, it should be taken out,
* placed in its own source file, and the "__inline" declaration removed
* so the function will be globally available.
*/
#pragma comment( lib, "USER32" )
#include
#define MTASSERT(a) _ASSERTE(a)
#define MTVERIFY(a) if (!(a)) PrintError(#a,__FILE__, __LINE__, GetLastError())
__inline void PrintError(LPSTR linedesc, LPSTR filename, int lineno, DWORD errnum)
{
LPSTR lpBuffer;
char errbuf[256];
#ifdef _WINDOWS
char modulename[MAX_PATH];
#else // _WINDOWS
DWORD numread;
#endif // _WINDOWS
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
errnum,
LANG_NEUTRAL,
(LPTSTR)&lpBuffer,
0,
NULL );
wsprintf(errbuf, " The following call failed at line %d in %s: "
" %s Reason: %s ", lineno, filename, linedesc, lpBuffer);
#ifndef _WINDOWS
WriteFile(GetStdHandle(STD_ERROR_HANDLE), errbuf, strlen(errbuf), &numread, FALSE );
Sleep(3000);
#else
GetModuleFileName(NULL, modulename, MAX_PATH);
MessageBox(NULL, errbuf, modulename, MB_ICONWARNING|MB_OK|MB_TASKMODAL|MB_SETFOREGROUND);
#endif
exit(EXIT_FAILURE);
}
--------------------------------------------------------------------------------
说明:其中输出到stderr和MessageBox部分可以把错误信息Log到文件或者其他存储中,以备分析错误记录。
MTVERIFY宏的使用前提是:产生的错误可以由GetLastError()捕捉。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/777154/viewspace-934617/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/777154/viewspace-934617/