Thread.setDefaultUncaughtExceptionHandler in Spring
-
28-04-2021 - |
Question
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?
Solution
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...)
OTHER TIPS
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
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow