Skip to content

Instantly share code, notes, and snippets.

@Gnomorian
Created August 16, 2021 10:47
Show Gist options
  • Save Gnomorian/38e0672d9652d707f853fdb4827e56e2 to your computer and use it in GitHub Desktop.
Save Gnomorian/38e0672d9652d707f853fdb4827e56e2 to your computer and use it in GitHub Desktop.
an exception that takes (or gets automatically) the windows error code and populates what() with the error message so you can throw on win32 errors and get useful information in the catch without code repeat.
#pragma once
/* an exeption object that gets the error message for windows error codes. */
/* default constructor will get the error code from windows, alternativly you can provide the error code. */
/* exmple:
#include "win32exception.h"
#include <iostream>
int main()
{
try
{
throw Win32Exception{ 0 };
}
catch (Win32Exception& e)
{
std::cout << e.what();
}
}
*/
#include <stdexcept>
#include <Windows.h>
class Win32Exception : public std::exception
{
uint32_t errorCode{0u};
void* msgBuffer{ nullptr };
public:
Win32Exception()
: errorCode{ GetLastError() }
{
getMessageForCode();
}
explicit Win32Exception(uint32_t errorCode)
: errorCode{errorCode}
{
getMessageForCode();
}
~Win32Exception()
{
LocalFree(msgBuffer);
}
char const* what() const override
{
return static_cast<char const*>(msgBuffer);
}
protected:
void getMessageForCode()
{
constexpr auto Flags{
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS };
constexpr void* NoSource{ nullptr };
constexpr auto MsgLanguage{ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) };
constexpr auto NoSize{ 0 };
constexpr va_list* VaList{ nullptr };
FormatMessageA(Flags, NoSource, errorCode, MsgLanguage, (LPSTR)&msgBuffer, NoSize, VaList);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment