CLastError

·2 min read·paskov

CLastError is a small MFC helper class that converts Win32 error codes, including those returned by ::GetLastError(), into readable messages. It provides two static methods.

The Get method uses FormatMessage() to retrieve a system message for the supplied error code and stores it in strErrMessage. If the lookup fails, it stores a fallback message containing the error code.

void CLastError::Get(const DWORD& dwErrorCode, CString& strErrMessage)
{
    LPTSTR lpErrorText = NULL;
    const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_ALLOCATE_BUFFER
        | FORMAT_MESSAGE_IGNORE_INSERTS;

    const DWORD dwLength = ::FormatMessage(
        dwFlags, NULL, dwErrorCode, 0,
        reinterpret_cast<LPTSTR>(&lpErrorText), 0, NULL);

    if (dwLength != 0)
    {
        strErrMessage = lpErrorText;
        ::LocalFree(lpErrorText);
    }
    else
    {
        strErrMessage.Format(_T("Windows error %lu."), dwErrorCode);
    }
}

The Show method calls Get, formats the message with the application name, and displays it using AfxMessageBox().

void CLastError::Show(const DWORD& dwErrorCode, const CString& strAppName)
{
    CString strErrMessage;
    Get(dwErrorCode, strErrMessage);

    CString strDisplayError;
    strDisplayError.Format(
        _T("%s encountered an error and needs to close!\n\nError was: %s"),
        static_cast<LPCTSTR>(strAppName),
        static_cast<LPCTSTR>(strErrMessage));

    AfxMessageBox(strDisplayError, MB_ICONERROR | MB_OK);
}

Class declaration:

class CLastError
{
public:
    CLastError();
    virtual ~CLastError();

    static void Get(const DWORD& dwErrorCode, CString& strErrMessage);
    static void Show(const DWORD& dwErrorCode, const CString& strAppName);
};

Class implementation:

CLastError::CLastError()
{
}

CLastError::~CLastError()
{
}

void CLastError::Get(const DWORD& dwErrorCode, CString& strErrMessage)
{
    LPTSTR lpErrorText = NULL;
    const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM
        | FORMAT_MESSAGE_ALLOCATE_BUFFER
        | FORMAT_MESSAGE_IGNORE_INSERTS;

    const DWORD dwLength = ::FormatMessage(
        dwFlags, NULL, dwErrorCode, 0,
        reinterpret_cast<LPTSTR>(&lpErrorText), 0, NULL);

    if (dwLength != 0)
    {
        strErrMessage = lpErrorText;
        ::LocalFree(lpErrorText);
    }
    else
    {
        strErrMessage.Format(_T("Windows error %lu."), dwErrorCode);
    }
}

void CLastError::Show(const DWORD& dwErrorCode, const CString& strAppName)
{
    CString strErrMessage;
    Get(dwErrorCode, strErrMessage);

    CString strDisplayError;
    strDisplayError.Format(
        _T("%s encountered an error and needs to close!\n\nError was: %s"),
        static_cast<LPCTSTR>(strAppName),
        static_cast<LPCTSTR>(strErrMessage));

    AfxMessageBox(strDisplayError, MB_ICONERROR | MB_OK);
}

Related Posts

Comments 1

  1. kzkazBrope

    thanks, interesting read