java - Java 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 - Handler 是这样的:
private void exceptionHandler(MyCustomRuntimeException ex) {
//some Magic
}
每次在此类中抛出 MyCustomRuntimeException 时都应该使用它。我知道我可以在每种方法中使用 try、catch、finally,但是是否有一个类范围的解决方案?想跳过样板
try {
...
} catch (MyCustomRuntimeException ex) {
exceptionHandler(ex);
}
我在这个应用程序中使用了 Spring(没有 Spring Boot),但是我没有发现如何使用@ExceptionHandler
普通的 Spring。我尝试了以下方法(不起作用):
易应用
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();
}
}
富吧
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!");
}
}
我的配置
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();
}
}
解决方案
如果您不使用 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
这个。春季教程
@ExceptionHandler
可以处理特定类和全局处理程序(通过@ControllerAdvice
)
类特定的处理程序在全局处理程序之前触发。所以最佳实践是在全局处理程序中使用RuntimeException
和Exception
,而不是在单个类中使用它们。进一步减少样板。
推荐阅读
- javascript - npm install create-react-app my_app 在 fsevents 上有货
- c++ - 在 C++ 中使用循环进行内存分配
- java - Css 不适用于 ReloadableResourceBundleMessageSource
- html - 画布强制网格单元无限扩展
- chromium - Cefsharp 多个 BrowserSubProcesses 使用所有内存
- excel - 通过 filedialog 导入两个文件后合并两个文件并将结果复制到另一个工作簿
- java - 为什么 java/sql 模块默认不从自动模块解析,还有其他系统模块默认不解析
- linux - 使用 sed 删除特定位数
- python - 我正在尝试使用 math.pow 找到 2 个数字的幂和它的模 ((x**y)%z) 并给出错误
- php - php:如何降低具有大量设置器的方法的圈复杂度