7 #include <winapi/utf8.hpp>
14 #include <system_error>
20 std::wstring trim_trailing_newline(
const std::wstring& s) {
21 const auto last_pos = s.find_last_not_of(L
"\r\n");
22 if (std::wstring::npos == last_pos)
24 return s.substr(0, last_pos + 1);
27 std::string build_what(DWORD code,
const char*
function) {
28 std::ostringstream what;
29 what <<
"Function " <<
function <<
" failed with error code " << code;
33 std::string format_message(int32_t code) {
36 const auto len = ::FormatMessageW(
37 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
40 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
41 reinterpret_cast<wchar_t*
>(&buf),
47 return "Couldn't format the error message";
50 std::wstring msg{buf, len};
52 return narrow(trim_trailing_newline(msg));
57 std::string CategoryWindows::message(int32_t code)
const {
58 return format_message(code);
61 std::system_error
windows(DWORD code,
const char*
function) {
62 static_assert(
sizeof(DWORD) ==
sizeof(int32_t),
"Aren't DWORDs the same size as ints?");
63 return std::system_error{
64 static_cast<int32_t
>(code), category_windows(), build_what(code,
function)};
Make std::system_error work with GetLastError().
std::system_error windows(DWORD code, const char *function)