Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to post some debugging information into a log using MFC's CString, but I can't seem to find if it preserves error code set by the last WinAPI (and retrievable with GetLastError)?

EDIT: Here's a code example of a simplified version of what I'm currently doing in my existing project:

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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

One convenient solution would be to define a class that contains both a CString and a last error code, then overload logError and redefine collectDebuggerInfo something like this:

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

This way you don't have to change the code that invokes the error handling functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...