-1

我需要使用 MFC 的CString将一些调试信息发布到日志中,但我似乎无法找到它是否保留了最后一个 WinAPI 设置的错误代码(并且可以使用GetLastError检索)?

编辑:这是我目前在现有项目中所做的简化版本的代码示例:

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?
}
4

1 回答 1

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

这样您就不必更改调用错误处理函数的代码。

于 2014-07-22T04:49:46.583 回答