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 <ae@cy.md>
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 /// Encapsulates a Windows API error code.
24 /// Populates the message with an OS-provided error string.
25 class WindowsException : Exception
26 {
27 	DWORD code; /// The error code.
28 
29 	this(DWORD code, string str=null)
30 	{
31 		this.code = code;
32 
33 		wchar *lpMsgBuf = null;
34 		FormatMessageW(
35 			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
36 			null,
37 			code,
38 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
39 			cast(LPWSTR)&lpMsgBuf,
40 			0,
41 			null);
42 
43 		auto message = lpMsgBuf.fromWString();
44 		if (lpMsgBuf)
45 			LocalFree(lpMsgBuf);
46 
47 		message = strip(message);
48 		message ~= format(" (error %d)", code);
49 		if (str)
50 			message = str ~ ": " ~ message;
51 
52 		super(message);
53 	} ///
54 }
55 
56 /// `enforce` variant using `GetLastError`.
57 T wenforce(T)(T cond, string str=null)
58 {
59 	if (cond)
60 		return cond;
61 
62 	throw new WindowsException(GetLastError(), str);
63 }