使用spring aop拦截异常

使用spring aop拦截异常

一、引入相应的jar包

        <!-- AspectJ begin -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.10</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- AspectJ end -->

二、修改spring配置文件

添加如下配置

  <aop:aspectj-autoproxy />   
  <context:component-scan base-package="mfy"/>

三、定义切面类

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class ExceptionAspect { 

    private static Logger LOG = LoggerFactory
            .getLogger(ExceptionAspect.class);

    @Pointcut("execution(* process.spring.exception.*Delegate.*(..))")
    public void pointCut() {
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "error")
    public void afterThrowing(JoinPoint jp, Throwable error) {
        LOG.error("ExceptionAspect error");
        if (null != jp.getArgs() && jp.getArgs().length > 0) {
            Object firstArg = jp.getArgs()[0];
            String errorStack = this.getExceptionStack(error);   
            LOG.error(errorStack);
            LOG.error(firstArg);
        }
    }

    private String getExceptionStack(Throwable error) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        PrintStream ps = new PrintStream(baos);  
        error.printStackTrace(ps);  
        String errorStack = baos.toString();  
        ps.close();
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return errorStack;
    }

}

最后,运行抛出异常的类即可打印出切面类中的异常。

    原文作者:lxxxzzl
    原文地址: https://blog.csdn.net/lxxxzzl/article/details/44724451
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞