[英]Where can I catch non rest controller exceptions in spring?
我有 spring mvc 應用程序。 為了捕獲異常,我使用@ExceptionHandler
注釋。
@ControllerAdvise
public class ExceptionHandlerController {
@ExceptionHandler(CustomGenericException.class)
public ModelAndView handleCustomException(CustomGenericException ex) {
....
}
}
但我認為我只會在控制器方法調用后捕獲異常。
但是如何捕獲在 rest 上下文之外生成的異常呢? 例如生命周期回調或計划任務。
但是如何捕獲在 rest 上下文之外生成的異常呢? 例如生命周期回調或計划任務
我能想到的一種解決方案是使用After Throwing Advice 。 基本思想是定義一個通知來捕獲某些 bean 拋出的異常並適當地處理它們。
例如,您可以定義一個自定義注釋,如:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Handled {}
並使用該注釋來標記應該建議的方法。 然后你可以用這個注釋來注釋你的工作:
@Component
public class SomeJob {
@Handled
@Scheduled(fixedRate = 5000)
public void doSomething() {
if (Math.random() < 0.5)
throw new RuntimeException();
System.out.println("I escaped!");
}
}
最后定義一個通知來處理由@Handled
注釋的方法拋出的異常:
@Aspect
@Component
public class ExceptionHandlerAspect {
@Pointcut("@annotation(com.so.Handled)")
public void handledMethods() {}
@AfterThrowing(pointcut = "handledMethods()", throwing = "ex")
public void handleTheException(Exception ex) {
// Do something useful
ex.printStackTrace();
}
}
為了對方法執行進行更精細的控制,您也可以使用Around Advice 。 另外不要忘記啟用自動@EnableAspectJAutoProxy
,在 Java 配置上使用@EnableAspectJAutoProxy
或在 XML 配置中使用<aop:aspectj-autoproxy/>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.