利用FormatMessage函数得到错误代码的文本显示


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);

[@more@]

/*
* 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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值