首页 > 解决方案 > 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();
    }
}

标签: javaspringexception

解决方案


如果您不使用 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

类特定的处理程序在全局处理程序之前触发。所以最佳实践是在全局处理程序中使用RuntimeExceptionException,而不是在单个类中使用它们。进一步减少样板。


推荐阅读