Click here to Skip to main content
12,703,102 members (29,534 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked

GetLastError as std::string

, 19 Oct 2012 BSD
Rate this:
Please Sign up or sign in to vote.
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(
        (LPTSTR) &lpMsgBuf,
        0, NULL );
    if (bufLen)
      LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf;
      std::string result(lpMsgStr, lpMsgStr+bufLen);

      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.


This article, along with any associated source code and files, is licensed under The BSD License


About the Author

Orjan Westin
Software Developer (Senior)
United Kingdom United Kingdom
Orjan has worked as a professional developer - in Sweden and England - since 1993, using a wide range of languages (C++, Pascal, Delphi, C, C#, Visual Basic, PHP, Python and x86 assembler), but tends to return to C++.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 19 Oct 2012
Article Copyright 2012 by Orjan Westin
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid