65.9K
CodeProject is changing. Read more.
Home

GetLastError as std::string

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (7 votes)

Oct 19, 2012

BSD
viewsIcon

49728

Simple function to get the text message corresponding to a system error.

This function retrieves the last error code, if any, and gets the text message associated with it, which is then converted to a standard string and returned.

The main benefits of using this function is that it saves you from having to remember the syntax of FormatMessage, and that the memory reserved is tidied up.

// Needs Windows constant and type definitions
#include <windows.h>

// Create a string with last error message
std::string GetLastErrorStdStr()
{
  DWORD error = GetLastError();
  if (error)
  {
    LPVOID lpMsgBuf;
    DWORD bufLen = FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        error,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );
    if (bufLen)
    {
      LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf;
      std::string result(lpMsgStr, lpMsgStr+bufLen);
      
      LocalFree(lpMsgBuf);

      return result;
    }
  }
  return std::string();
}

Note that the FORMAT_MESSAGE_FROM_SYSTEM flag means only system error messages will be given. If you want to include error messages from your own modules, you'll need to add the FORMAT_MESSAGE_FROM_HMODULE flag, and provide the handle to the module. See the FormatMessage documentation for details.