I am developing a Spring application, and was wondering if there a part of the framework that let's me do something like this in a more elegant way, such as configuring something in XML?
Asked
Active
Viewed 6,081 times
8
-
In what context? What actual problem are you trying to solve? – skaffman Feb 10 '12 at 14:08
-
Sorry I should have elaborated. In this case I am writing an uncaught exception handler which writes the stack trace to my log4j file. While straightforward to implement I was wondering if there was a "Spring way" of doing things. – mogronalol Feb 12 '12 at 00:04
2 Answers
8
If the purpose of your question is to set a custom UncaughtExceptionHandler
through your application context, you can use:
<bean id="myhandler" class="java.lang.ThreadGroup">
<constructor-arg value="Test"/>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.Thread"/>
<property name="targetMethod" value="setDefaultUncaughtExceptionHandler"/>
<property name="arguments">
<list>
<ref bean="myhandler" />
</list>
</property>
</bean>
(N.B. replace myhandler with an Thread.UncaughtExceptionHandler
of choice...)

beny23
- 34,390
- 5
- 82
- 85
-
4This is the "more elegant way"? How is this better than doing it in Java? – skaffman Feb 12 '12 at 00:10
-
Without context I've not really got an opinion on whether it is elegant or not, but I can see the reasoning of doing this versus creating a separate Java class just to set the uncaught exception handler on startup. – beny23 Feb 13 '12 at 09:48
-
I do think this is more elegant, as setting the handler is part of your applications configuration which spring is supposed to be in control off. – mogronalol Feb 14 '12 at 14:01
0
You can also use @ControllerAdvice
annotated classes for uncaught exception handling. Referencing from https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc, the following code will catch any Exception:
@ControllerAdvice
public class MyUncaughtExceptionHandler {
@ExceptionHandler(value = Exception.class)
public void defaultExceptionHandler(Exception e) {
// do whatever you want with the exception
}
}

Eren Yilmaz
- 1,082
- 12
- 21