【问题标题】:Java ExceptionHandler whole ClassJava ExceptionHandler 整个类
【发布时间】:2020-05-29 14:49:56
【问题描述】:

有没有办法为 Class 和 Exceptionclass 设置 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),但我没有发现如何将 @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();
    }
}

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!");
     }
}

我的配置

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();
    }
}

【问题讨论】:

    标签: java spring exception


    【解决方案1】:

    如果你没有使用 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的时候

    您可以为此使用@ExceptionHandlerSpring Tutorial

    @ExceptionHandler 可以处理特定类和全局处理程序(通过@ControllerAdvice

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

    【讨论】:

    • 是的,我以前读过,但是我如何在没有 Boot、Controller、RequestMapping 等的情况下使用它?我在上面添加了一个示例应用程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2021-12-02
    • 2016-12-16
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多