1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package ch.elca.el4j.services.exceptionhandler.handler;
19
20 import java.lang.reflect.Constructor;
21
22 import org.slf4j.Logger;
23 import org.springframework.beans.factory.InitializingBean;
24
25 import ch.elca.el4j.services.monitoring.notification.CoreNotificationHelper;
26
27
28
29
30
31
32
33
34 public class SimpleExceptionTransformerExceptionHandler
35 extends AbstractExceptionTransformerExceptionHandler
36 implements InitializingBean {
37
38
39 private Class m_transformedExceptionClass;
40
41
42
43
44
45
46
47 public void setTransformedExceptionClass(Class transformedClass) {
48 m_transformedExceptionClass = transformedClass;
49 }
50
51
52
53
54 protected Exception transform(Throwable t, Logger logger) {
55 Exception e = createExceptionWithMessageAndThrowable(t);
56 if (e == null) {
57 e = createExceptionWithMessage(t);
58 }
59 if (e == null) {
60 e = createException();
61 }
62 if (e == null) {
63 logger.warn("Unable to transform Exception from ["
64 + t.getClass().getName() + "] to ["
65 + m_transformedExceptionClass.getName() + "].");
66 return null;
67 }
68 e.setStackTrace(t.getStackTrace());
69
70 return e;
71 }
72
73
74
75
76 public void afterPropertiesSet() throws Exception {
77 CoreNotificationHelper.notifyIfEssentialPropertyIsEmpty(
78 m_transformedExceptionClass, "transformedClass", this);
79 if (!Exception.class.isAssignableFrom(m_transformedExceptionClass)) {
80 CoreNotificationHelper.notifyMisconfiguration(
81 "The property 'transformedClass' has to be an instance of"
82 + " java.lang.Exception.");
83 }
84
85 m_transformedExceptionClass.newInstance();
86 }
87
88
89
90
91
92
93
94
95
96
97
98 private Exception createExceptionWithMessageAndThrowable(Throwable t) {
99 Exception e = null;
100 Class[] params = {String.class, Throwable.class};
101 Object[] values = {t.getMessage(), t};
102
103 try {
104 Constructor c = m_transformedExceptionClass.getConstructor(params);
105 e = (Exception) c.newInstance(values);
106 } catch (Exception ex) { }
107 return e;
108
109 }
110
111
112
113
114
115
116
117
118
119
120 private Exception createExceptionWithMessage(Throwable t) {
121 Exception e = null;
122 Class[] params = {String.class};
123 Object[] values = {t.getMessage()};
124
125 try {
126 Constructor c = m_transformedExceptionClass.getConstructor(params);
127 e = (Exception) c.newInstance(values);
128 } catch (Exception ex) { }
129
130 return e;
131 }
132
133
134
135
136
137 private Exception createException() {
138 Exception e = null;
139
140 try {
141 e = (Exception) m_transformedExceptionClass.newInstance();
142 } catch (Exception ex) { }
143
144 return e;
145 }
146 }