我需要使用MFC的CString将一些调试信息发布到日志中,但我似乎找不到它是否保留了最后WinAPI设置的错误代码(并可与GetLastError检索)?
EDIT:以下是我目前在现有项目中所做的简化版本的代码示例:
HANDLE hFile = CreateFile(strFilePath, ...);
if(hFile == INVALID_HANDLE_VALUE)
{
logError(collectDebuggerInfo(strFilePath));
}
void logError(LPCTSTR pStrDesc)
{
int nLastError = ::GetLastError();
CString str;
str.Format(L"LastError=%d, Description: %s", nLastError, pStrDesc);
//Add 'str' to the logging file...
}
CString collectDebuggerInfo(LPCTSTR pFilePath)
{
int nLastError = ::GetLastError();
CString str;
str.Format(L"Debugging info for file: "%s"", pFilePath);
::SetLastError(nLastError);
return str; //RETURNING CString -- will it overwrite the last error?
}
一个方便的解决方案是定义一个既包含CString又包含最后一个错误码的类,然后重载logError
并像这样重新定义collectDebuggerInfo
:
void logError(StringWithEmbeddedErrorCode instr)
{
LPCTSTR pStrDesc = instr.str;
SetLastError(instr.nLastError);
logError(pStrDesc);
}
StringWithEmbeddedErrorCode collectDebuggerInfo(LPCTSTR pFilePath)
{
int nLastError = ::GetLastError();
CString str;
str.Format(L"Debugging info for file: "%s"", pFilePath);
return StringWithEmbeddedErrorCode(str, nLastError);
}
这样,您就不必更改调用错误处理函数的代码。