1 /**
2  * Windows exceptions.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.sys.windows.exception;
15 version (Windows):
16 
17 import core.sys.windows.windows;
18 
19 import std.string;
20 
21 import ae.sys.windows.text;
22 
23 class WindowsException : Exception
24 {
25 	DWORD code;
26 
27 	this(DWORD code, string str=null)
28 	{
29 		this.code = code;
30 
31 		wchar *lpMsgBuf = null;
32 		FormatMessageW(
33 			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
34 			null,
35 			code,
36 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
37 			cast(LPWSTR)&lpMsgBuf,
38 			0,
39 			null);
40 
41 		auto message = lpMsgBuf.fromWString();
42 		if (lpMsgBuf)
43 			LocalFree(lpMsgBuf);
44 
45 		message = strip(message);
46 		message ~= format(" (error %d)", code);
47 		if (str)
48 			message = str ~ ": " ~ message;
49 
50 		super(message);
51 	}
52 }
53 
54 T wenforce(T)(T cond, string str=null)
55 {
56 	if (cond)
57 		return cond;
58 
59 	throw new WindowsException(GetLastError(), str);
60 }