2017-06-19 38 views
0

我正在處理Spring應用程序,並且想要以下列方式實現異常處理: 針對異常被轉移的特定異常類型實現Aspect類 有這樣的方面基於異常類型層次結構的類和實現catch塊的行爲 例如, 有兩個方面類:異常的ExceptionHandler和SQLException的SQLExceptionHandler 兩者都是完全相同的切入點表達式。 現在,如果SQLException是由點表達式中涵蓋的任何方法引發的,則應執行SQLExceptionHandler的方法。 如果發生FileNotFoundException或任何其他類型的異常,則應執行ExceptionHandler的方法。 任何幫助將不勝感激。使用AOP在Spring中實現「catch block」類似行爲

+0

這是一個太寬泛的問題。看起來像一個任務。但要提出一個想法:你可以實現一個'BeanPostProcessor',它將用一個包含方法調用的調用處理程序包裝你的帶註釋的類到try-catch塊中。 –

回答

0

您可以嘗試擴展OncePerRequestFilter類並覆蓋doFilterInternal方法。像下面的東西會做的伎倆:

public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, 
      final FilterChain filterChain) throws ServletException, IOException { 

    try { 
     filterChain.doFilter(request, response); 
    } catch (ExceptionType1 e) { 
    // Any exception thrown from your code can be handled or retrhown from here. 
    } catch (ExceptionType2 e) { 
    // Any exception thrown from your code can be handled or retrhown from here. 
    } catch ...... 
}