簡體   English   中英

Java ExceptionHandler 整個 Class

[英]Java ExceptionHandler whole Class

有沒有辦法為 Class 和 Exceptionclass 設置 ExceptionHandler? 我有一個像這樣的 class :

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
}

每次在此 class 中引發 MyCustomRuntimeException 時都應使用它。 我知道我可以在每種方法中使用 try, catch, finally,但是是否有 Class 廣泛的解決方案? 想跳過樣板

try {
...
} catch (MyCustomRuntimeException ex) {
    exceptionHandler(ex);
}

我在此應用程序中使用 Spring(沒有 Spring 引導),但我沒有發現如何將@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 Spring教程

@ExceptionHandler可以處理 class 特定和全局處理程序(通過@ControllerAdvice

class 特定的處理程序在全局處理程序之前觸發。 所以最佳實踐是在全局處理程序中使用RuntimeExceptionException ,而不是在單個類中使用它們。 進一步減少樣板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM