使用AOP在Spring中实现类似行为的“Catch Block”

时间:2017-06-19 14:21:20

标签: spring exception-handling spring-aop

我正在使用Spring应用程序,我想以下列方式实现异常处理: 为转移该异常的特定异常类型实现Aspect类 具有基于异常类型层次结构的此类方面类,并实现类似行为的catch块 例如, 有两个方面类:Exception的ExceptionHandler和SQLException的SQLExceptionHandler 它们都是完全相同的切入点表达式。 现在,如果从点表达式中涉及的任何方法引发SQLException,则应执行SQLExceptionHandler的方法。 如果发生FileNotFoundException或任何其他类型的异常,则应执行ExceptionHandler的方法。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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 ......
}
相关问题