1 /*
2  * Collie - An asynchronous event-driven network framework using Dlang development
3  *
4  * Copyright (C) 2015-2017  Shanghai Putao Technology Co., Ltd 
5  *
6  * Developer: putao's Dlang team
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 module collie.utils.exception;
12 import kiss.log;
13 public import std.exception : basicExceptionCtors;
14 
15 mixin template ExceptionBuild(string name, string parent = "")
16 {
17 	enum buildStr = "class " ~ name ~ "Exception : " ~ parent ~ "Exception { \n\t" ~ "mixin basicExceptionCtors;\n }";
18 	mixin(buildStr);
19 }
20 
21 mixin template ThrowExceptionBuild()
22 {
23 	pragma(inline, true)
24 		void throwExceptionBuild(string name = "")(string msg = "",string file = __FILE__, size_t line = __LINE__ )
25 	{
26 		mixin("throw new " ~ name ~ "Exception(msg,file,line);");
27 	}
28 }
29 
30 pragma(inline)
31 	void showException(bool gcfree = false,int line = __LINE__, string file = __FILE__,
32 		string funcName = __FUNCTION__)(Exception e) nothrow
33 {
34 	
35 	import std.exception;
36 	collectException(logError(e.toString));
37 	static if(gcfree){
38 		import collie.utils.memory;
39 		collectException(gcFree(e));
40 	}
41 
42 }
43 
44 string buildErroCodeException(T)() if(is(T == enum))
45 {
46 	string str = "mixin ExceptionBuild!(\"" ~ T.stringof ~ "\");\n";
47 	foreach(memberName; __traits(derivedMembers,T)){
48 		str ~= "mixin ExceptionBuild!(\"" ~ memberName ~ "\", \"" ~ T.stringof ~ "\");\n";
49 	}
50 	return str;
51 }
52 
53 
54 version(unittest)
55 {
56 	enum Test{
57 		MyTest1,
58 		MyTest2,
59 	}
60 	//mixin ExceptionBuild!"MyTest1";
61 	//mixin ExceptionBuild!"MyTest2";
62 	mixin(buildErroCodeException!Test());
63 	mixin ThrowExceptionBuild;
64 }
65 
66 unittest
67 {
68 	import std.stdio;
69 	import std.exception;
70 	auto e = collectException!TestException(throwExceptionBuild!"Test"("test Exception"));
71 	assert(e !is null);
72 	auto e1 = collectException!MyTest1Exception(throwExceptionBuild!"MyTest1"("test Exception"));
73 	assert(e1 !is null);
74 	auto e2 = collectException!MyTest2Exception(throwExceptionBuild!"MyTest2"("test Exception"));
75 	assert(e2 !is null);
76 }