有没有办法为类和异常类设置ExceptionHandler?我有一个这样的类:
public class MyServiceClass {
public void foo() {
//some Code...
throw new MyCustomRuntimeException();
//some more Code...
}
public void foo2() {
//some other Code...
throw new MyCustomRuntimeException();
//more other Code...
}
}现在我想定义一个类似这样的MyCustomRuntimeException处理程序:
private void exceptionHandler(MyCustomRuntimeException ex) {
//some Magic
}每次在这个类中抛出MyCustomRuntimeException时都应该使用它。我知道我可以在每个方法中使用try,catch,finally,但是有一个类范围的解决方案吗?我想跳过样板文件
try {
...
} catch (MyCustomRuntimeException ex) {
exceptionHandler(ex);
}我在这个应用程序中使用了Spring (没有Spring Boot),但是我没有发现如何在普通的Spring中使用@ExceptionHandler。我尝试了以下方法(不起作用):
EasyApplication
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class EasyApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
FooBar foo = context.getBean(FooBar.class);
foo.doException();
}
}FooBar
import org.springframework.web.bind.annotation.ExceptionHandler;
public class FooBar {
public void doException() {
throw new RuntimeException();
}
@ExceptionHandler(value = RuntimeException.class)
public void conflict() {
System.out.println("Exception handled!");
}
}MyConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean(name = "FooBar")
public FooBar fooBar() {
return new FooBar();
}
}发布于 2020-05-29 23:10:41
如果您没有使用spring-mvc,并且不是在多线程环境中,那么您将能够很好地完成以下工作。
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("This is from the uncaught");
}
}然后在您的main方法中添加这一行。这适用于小型应用程序,而spring在这方面的作用很小。
Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());如果你有一个更大的应用程序,并且需要一个更优雅的解决方案--在你的应用程序中引入方面(AOP)。
编辑: 2020年6月2日
这是使用spring-mvc的时候。
您可以使用@ExceptionHandler来实现这一点。Spring Tutorial
(通过@ControllerAdvice) @ExceptionHandler可以处理类特定处理程序和全局处理程序
类特定的处理程序在全局处理程序之前触发。因此,最佳实践是在全局处理程序中使用RuntimeException和Exception,而不是在单个类中使用它们。进一步减少样板文件。
https://stackoverflow.com/questions/62088688
复制相似问题