spring aop 捕获异常

来源:互联网 发布:淘宝知识产权侵权申诉 编辑:程序博客网 时间:2024/06/05 04:21

 <bean id="exceptionHandler" class="highsoft.uip.common.ExceptionHandler" />
 <bean id="autoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />

  <!-- 这里配置切入点,可以为正则表达式 .*DAOImpl\.delete.*-->
   <bean id="exceptionHandlereAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
   <property name="advice">
       <ref bean="exceptionHandler"/>
    </property>
      <property name="patterns">
  <list>
   <value>.*.*</value>
  </list>
   </property>
 </bean>

 

 

public class ExceptionHandler implements ThrowsAdvice { 
     /**
      * Owner 
      * 参数解释 Method method 执行的方法 
      * Object[] args 方法参数
      *  Object target 代理的目标对象
     * Throwable throwable 产生的异常 
      *
      */ 
     public void afterThrowing(Method method, Object[] args, Object target, RuntimeException  throwable) { 
         System.out.println("产生异常的方法名称:  " + method.getName()); 
         for(Object o:args){ 
            System.out.println("方法的参数:   " + o.toString()); 
        } 
          
        System.out.println("代理对象:   " + target.getClass().getName()); 
        System.out.println("抛出的异常:    " + throwable.getMessage()+">>>>>>>"  + throwable.getCause()); 

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
        if(request.getAttribute("exception")==null){
         ArrayList<String> eptList=new ArrayList<String> ();
         request.setAttribute("exception", eptList);
        }
        request.setAttribute("exception",(( ArrayList<String>)request.getAttribute("exception")).add(throwable.getMessage()));
        System.out.println("异常详细信息:   "+throwable.fillInStackTrace()); 
     } 
 } 

 

注意:此方法只对spring配置的bean进行捕获异常

原创粉丝点击