winapi_error.h
1 #pragma once 2 3 #define WIN32_LEAN_AND_MEAN 4 #include <Windows.h> 5 6 #include <optional> 7 #include <string> 8 #include <system_error> 9 #include <strsafe.h> 10 11 inline std::optional<std::wstring> get_last_error_message(const DWORD dw) 12 { 13 std::optional<std::wstring> message; 14 try 15 { 16 const auto msg = std::system_category().message(dw); 17 message.emplace(begin(msg), end(msg)); 18 } 19 catch (...) 20 { 21 } 22 return message; 23 } 24 25 inline std::wstring get_last_error_or_default(const DWORD dw) 26 { 27 auto message = get_last_error_message(dw); 28 return message.has_value() ? *message : L""; 29 } 30 31 inline void show_last_error_message(const wchar_t* functionName, DWORD dw, const wchar_t* errorTitle) 32 { 33 const auto system_message = get_last_error_message(dw); 34 if (!system_message.has_value()) 35 { 36 return; 37 } 38 LPWSTR lpDisplayBuf = static_cast<LPWSTR>(LocalAlloc(LMEM_ZEROINIT, (system_message->size() + lstrlenW(functionName) + 40) * sizeof(WCHAR))); 39 if (lpDisplayBuf != NULL) 40 { 41 StringCchPrintfW(lpDisplayBuf, 42 LocalSize(lpDisplayBuf) / sizeof(WCHAR), 43 L"%s: %s (%d)", 44 functionName, 45 system_message->c_str(), 46 dw); 47 MessageBoxW(NULL, lpDisplayBuf, errorTitle, MB_OK | MB_ICONERROR); 48 LocalFree(lpDisplayBuf); 49 } 50 }