1 /** Functions for throwing exceptions on WinAPI errors. 2 3 Copyright: Denis Shelomovskij 2013 4 5 License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0). 6 7 Authors: Denis Shelomovskij 8 */ 9 module unstd.windows.exception; 10 11 12 import core.sys.windows.windows; 13 14 import std.traits; 15 16 version(unittest) 17 { 18 import std.algorithm; 19 import std.exception; 20 } 21 22 23 /** 24 Exception thrown on WinAPI errors. 25 */ 26 class WinAPIException: Exception 27 { 28 this(in string functionName, in string file = __FILE__, in size_t line = __LINE__, Throwable next = null) @safe pure nothrow 29 { super("WinAPI function '" ~ functionName ~ "' failed.", file, line, next); } 30 } 31 32 /** 33 Convinient template to call WinAPI function and throw $(MREF WinAPIException) 34 on error. 35 */ 36 template enforceWinAPI(alias func) 37 if(functionLinkage!func == "Windows") 38 { 39 auto enforceWinAPI(ParameterTypeTuple!func args, in string file = __FILE__, in size_t line = __LINE__) 40 { 41 if(auto res = func(args)) 42 return res; 43 throw new WinAPIException(__traits(identifier, func), file, line); 44 } 45 } 46 47 /// 48 unittest 49 { 50 HANDLE processHeap = enforceWinAPI!GetProcessHeap(); 51 assert(processHeap); // Will always pass. 52 } 53 54 unittest 55 { 56 assert(enforceWinAPI!GetProcessHeap() == GetProcessHeap()); 57 assert(collectExceptionMsg!WinAPIException(enforceWinAPI!CloseHandle(null)).canFind("CloseHandle")); 58 } 59 60 version(unittest) 61 extern(Windows) nothrow extern HANDLE GetProcessHeap();