springboot学习笔记(四)——全局异常处理之AOP方式处理

前言:

        这一篇主要是写全局异常的处理的另一种AOP方式。代码和上一篇没什么大的改变,只是处理的方式由springboot提供的注解改成AOP的方式来进行异常捕获。


开发环境:    

        win10+IntelliJ IDEA +JDK1.8 

         springboot版本:springboot 1.5.14 ——2.0后的springboot增加了挺多新特性,暂时先不做了解


开始开发:

    

package com.wen.test.aop;

import com.wen.test.entity.ResultBean;
import com.wen.test.exception.CheckException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 切面
 */
@Slf4j  //日志注解
@Aspect     //切面
@Order(5)       //执行顺序
@Component      //一般不知道是哪个分类是,就用这玩意将他注入到spring容器中
public class HandlerException {

    /**
     * 切点,找到那些方面要切
     */
    @Pointcut("execution(public * com.wen.test.controller.*.*(..))")
    public void webException(){}

    /**
     * 环切,执行方法前后都切
     * @param proceedingJoinPoint
     * @return
     */
    @Around("webException()")
    public ResultBean handlerControllerMethod(ProceedingJoinPoint proceedingJoinPoint){
        ResultBean resultBean;
        try {
            long startTime = System.currentTimeMillis();
            resultBean= (ResultBean) proceedingJoinPoint.proceed();

            long endTime = System.currentTimeMillis()-startTime;

            log.info("最后花费的时间为:"+ endTime);
        }catch (Throwable e){
           resultBean= handlerException(e);
        }
        return resultBean;
    }

    /**
     * 这个是判断异常的类型
     * @param throwable
     * @return
     */
    private ResultBean<?> handlerException(Throwable throwable){
        ResultBean<?> resultBean=new ResultBean();
        if (throwable instanceof CheckException|| throwable instanceof IllegalArgumentException){
            resultBean.setMsg(throwable.getLocalizedMessage());
            resultBean.setCode(ResultBean.CHECK_FAIL);
        }else {
            log.error("未知异常:",throwable);
            resultBean.setMsg("未知异常,请联系管理员");
            resultBean.setCode(ResultBean.UNKNOWN_EXCEPTION);
        }
        return resultBean;


    }
}

            上面代码,不解释了吧。很简单。。看看就懂了。

本次案例代码:

https://github.com/LuckToMeet-Dian-N/springboot_Learn_4

总结:

        AOP在开发中很常见,springboot对AOP的支持也是不错的。但是终究感觉没有xml那么灵活。毕竟xml里配置了,不用的时候注释掉,一点也不妨碍我们的有业务代码。最后,祝大家学习进步,步步高升。


程序人生,与君共勉~



猜你喜欢

转载自blog.csdn.net/weixin_41622183/article/details/81048068