Spring Boot 通过 AOP 实现全局异常处理

一共有三种方式,这里详细介绍两种放弃,另外一种请自行百度

pom

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-aopartifactId>
dependency>

一、使用 @Aspect

这个类的前置准备需要,自定义的异常类(ClouduiBizException)、自定义返回结果处理类(ClouduiResult)


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.cloudui.common.util.ClouduiBizException;
import com.alipay.cloudui.common.util.base.BizErrorCode;
import com.alipay.cloudui.common.util.result.ClouduiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;


@Aspect
@Component
public class ClouduiControllerAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClouduiControllerAspect.class);

	//这里是指定切片的位置
    @Around("execution(* com.alipay.cloudui.web.controller.*.*(..))")
    public Object pointCut(ProceedingJoinPoint pjp) {
        try {
            Object result = pjp.proceed();
            if (LOGGER.isInfoEnabled())
                LOGGER.info("method: {}, params: {}, result: {}", pjp.getSignature(), JSON.toJSONString(pjp.getArgs(), SerializerFeature.IgnoreErrorGetter), result);
            return result;
        } catch (Throwable e) {
            LOGGER.error(pjp.getSignature() + "call fail!", e);
            if (e instanceof ClouduiBizException) {
                ClouduiBizException bizException = (ClouduiBizException) e;
                return ClouduiResult.buildFailure(bizException.getCode(), bizException.getMessage());
            } else
                return ClouduiResult.buildFailure(BizErrorCode.SYSTEM_ERROR.getCode(), MessageFormat.format(BizErrorCode.SYSTEM_ERROR.getMessage(), "unknown"));
        }
    }
}

二、使用 xml 文件配置

推荐,更灵活

不再需要 @Component 和 @Around 两个注解,在 xml 文件中配置



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.cloudui.common.util.ClouduiBizException;
import com.alipay.cloudui.common.util.base.BizErrorCode;
import com.alipay.cloudui.common.util.result.ClouduiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;


@Aspect
public class ClouduiControllerAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClouduiControllerAspect.class);

    //不需要注释指定切片位置
    public Object pointCut(ProceedingJoinPoint pjp) {
        try {
            Object result = pjp.proceed();
            if (LOGGER.isInfoEnabled())
                LOGGER.info("method: {}, params: {}, result: {}", pjp.getSignature(), JSON.toJSONString(pjp.getArgs(), SerializerFeature.IgnoreErrorGetter), result);
            return result;
        } catch (Throwable e) {
            LOGGER.error(pjp.getSignature() + "call fail!", e);
            if (e instanceof ClouduiBizException) {
                ClouduiBizException bizException = (ClouduiBizException) e;
                return ClouduiResult.buildFailure(bizException.getCode(), bizException.getMessage());
            } else
                return ClouduiResult.buildFailure(BizErrorCode.SYSTEM_ERROR.getCode(), MessageFormat.format(BizErrorCode.SYSTEM_ERROR.getMessage(), "unknown"));
        }
    }
}

(1)异常处理配置文件

如果有多个异常处理类,均可在这里注册

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sofa="http://schema.alipay.com/sofa/schema/slite"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://schema.alipay.com/sofa/schema/slite http://schema.alipay.com/sofa/slite.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"
       default-autowire="byName">


    <context:component-scan base-package="com.xxx.xxx.web"/>

    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <!--指定切片类-->
    <bean id="controllerAspect" class="com.xxx.xxx.web.ClouduiControllerAspect"/>
    <aop:config>
        <aop:aspect id="controllerException" ref="controllerAspect">
            <!--异常统一处理,声明切片的切入位置-->
            <aop:pointcut id="controller"
                          expression="execution(* com.alipay.cloudui.web.controller.*.*(..))"/>
            <aop:around pointcut-ref="controller" method="pointCut"/>
        </aop:aspect>
    </aop:config>
</beans>

三、@ControllerAdvice + @ExceptionHandler

你可能感兴趣的:(Java,spring,boot,java,spring)