-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwin32_error_exception.h
128 lines (109 loc) · 2.57 KB
/
win32_error_exception.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/** This file is part of dirCompare
*
* Copyright 2017-2020 Thomas Erbesdobler <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _WIN32_ERROR_EXCEPTION_H
#define _WIN32_ERROR_EXCEPTION_H
#include <exception>
#include <string>
#include <cstring>
extern "C"
{
#include <Windows.h>
}
class win32_error_exception : public std::exception
{
private:
char* msg;
void init(DWORD en, std::wstring wmsg = std::wstring())
{
LPWSTR wstr_msg = nullptr;
size_t cnt;
if ((cnt = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
0,
en,
0,
(LPWSTR) &wstr_msg,
0,
nullptr)))
{
wmsg += std::wstring(wstr_msg, cnt);
LocalFree(wstr_msg);
}
else
{
wmsg += L"Unable to format error message by error " + std::to_wstring(GetLastError());
}
auto end = wmsg.cend() - 1;
while (*end == L'\n' || *end == L'\r' || *end == L' ')
{
wmsg.pop_back();
end = wmsg.cend() - 1;
}
int utf8_size = WideCharToMultiByte(
CP_UTF8, 0, wmsg.c_str(), wmsg.length(),
nullptr, 0, nullptr, nullptr);
if (utf8_size == 0)
{
special_error();
return;
}
msg = new char[(size_t)utf8_size + 1];
msg[utf8_size] = '\0';
utf8_size = WideCharToMultiByte(
CP_UTF8, 0, wmsg.c_str(), wmsg.length(),
msg, utf8_size, nullptr, nullptr);
if (utf8_size == 0)
{
delete[] msg;
special_error();
return;
}
}
void special_error()
{
std::string s("Failed to convert error message to UTF-8: " + std::to_string(GetLastError()));
msg = new char[s.length() + 1];
msg[s.length()] = '\0';
strcpy(msg, s.c_str());
}
public:
win32_error_exception(DWORD en) : msg(nullptr)
{
init(en);
}
win32_error_exception(DWORD en, std::wstring str) : msg(nullptr)
{
init(en, str);
}
virtual ~win32_error_exception()
{
if (msg)
{
delete[] msg;
}
}
bool operator ==(const win32_error_exception& b)
{
return strcmp(msg, b.msg) == 0;
}
virtual const char* what() const throw() override
{
return msg;
}
};
#endif /* _WIN32_ERROR_EXCEPTION_H */