How should I use FormatMessage() properly in C++?

后端 未结 8 811
悲&欢浪女
悲&欢浪女 2020-11-28 03:28

Without:

  • MFC
  • ATL

How can I use FormatMessage() to get the error text for a HRESULT?

 HRES         


        
8条回答
  •  一生所求
    2020-11-28 04:12

    The code below is code is the C++ equivalent I've written out in contrast to Microsoft's ErrorExit() but slightly altered to avoid all macros and use unicode. The idea here is to avoid unnecessary casts and mallocs. I couldn't escape all of the C casts but this is the best I could muster. Pertaining to FormatMessageW(), which requires a pointer to be allocated by the format function and the Error Id from the GetLastError(). The pointer after static_cast can be used like a normal wchar_t pointer.

    #include 
    #include 
    
    void __declspec(noreturn) error_exit(const std::wstring FunctionName)
    {
        // Retrieve the system error message for the last-error code
        const DWORD ERROR_ID = GetLastError();
        void* MsgBuffer = nullptr;
        LCID lcid;
        GetLocaleInfoEx(L"en-US", LOCALE_RETURN_NUMBER | LOCALE_ILANGUAGE, (wchar_t*)&lcid, sizeof(lcid));
    
        //get error message and attach it to Msgbuffer
        FormatMessageW(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, ERROR_ID, lcid, (wchar_t*)&MsgBuffer, 0, NULL);
        //concatonate string to DisplayBuffer
        const std::wstring DisplayBuffer = FunctionName + L" failed with error " + std::to_wstring(ERROR_ID) + L": " + static_cast(MsgBuffer);
    
        // Display the error message and exit the process
        MessageBoxExW(NULL, DisplayBuffer.c_str(), L"Error", MB_ICONERROR | MB_OK, static_cast(lcid));
    
        ExitProcess(ERROR_ID);
    }
    

提交回复
热议问题