我需要使用MFC' CString将一些调试信息发布到日志中,但我似乎无法找到它是否保留了最后一个WinAPI设置的错误代码(并且可以通过{检索) {3}})?
编辑:以下是我现有项目中正在进行的简化版的代码示例:
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?
}
答案 0 :(得分:1)
一个方便的解决方案是定义一个包含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);
}
这样您就不必更改调用错误处理函数的代码。