1

I am making a program that uses winhttp library. To handle various exceptions, I have created a header file. The error is thrown by using GetLastError() function which is passed to the exception class as DWORD variable. But I want to print the description of error and not just the error number. I tried using FormatMessage function, its working for error 6 but not for others viz error 12002. I am using it like:

    WinHttpException(DWORD error)
    {
        LPTSTR lpszFunction = "Function";
        LPVOID lpMsgBuf;
        LPVOID lpDisplayBuf;
        DWORD dw = error; 

        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | 
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dw,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0, NULL );

        // Display the error message and exit the process

        lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
            (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); 

        StringCchPrintf((LPTSTR)lpDisplayBuf, 
            LocalSize(lpDisplayBuf) / sizeof(TCHAR),
            TEXT("%s failed with error %d: %s"), 
            lpszFunction, dw, lpMsgBuf); 

        MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

        m_message = boost::lexical_cast<std::string>(lpDisplayBuf);
    }

I got this code from this Microsoft link.. Is there any other way to do that? Or what arguments should i use in FormatMessage function to make this work? Thanks in advance.

1 Answers1

3

WinHTTP error messages are contained in the winhttp.dll module and FormatMessage() function allows you to retrieve them using FORMAT_MESSAGE_FROM_HMODULE flag (as per FormatMessage() documentation):

FormatMessage(
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_HMODULE |
    FORMAT_MESSAGE_IGNORE_INSERTS,
    GetModuleHandle(TEXT("winhttp.dll")),
    dw,
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    reinterpret_cast<LPTSTR>(&lpMsgBuf),
    0, NULL);
PowerGamer
  • 2,106
  • 2
  • 17
  • 33
  • Are you sure the `reinterpret_cast` call is needed here? I haven't needed it in my code or seen it used in other SO answers on this topic – Hawkins Jun 26 '18 at 17:24
  • @Hawkins That cast is not needed indeed, not sure why I put it there originally. I edited the answer and removed it. – PowerGamer Jun 26 '18 at 21:23