烦于项目每个接口捕捉异常?试试Spring Aop简单统一处理异常

该博客介绍了如何使用Spring AOP在Java项目中创建一个切面类,用于统一处理自定义和系统异常。通过定义切点并使用@Around注解进行环绕通知,实现了在控制器层捕获并转换异常为特定的错误响应。示例代码展示了如何在测试接口中抛出异常,并在实际运行时观察处理效果。
摘要由CSDN通过智能技术生成

第一步:定义切面类

package com.esell.pxb.pss.common.Aspect;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.StrUtil;
import com.esell.exception.Code;
import com.esell.exception.EsellException;
import com.esell.message.ApiResponse;
import com.esell.pxb.pss.common.util.PssUtil;
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.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 切面统一处理自定义/系统异常
 * @author ***
 * @create 2021−04-16 上午10:12
 */
@Aspect
@RestController
@Slf4j
public class PssExceptionAspect {

    //定义切点
	@Pointcut("execution(* com.esell.pxb.pss.controller.goods.PssGoodsController.*(..))")
	private void pointcut(){}
    
	@Around("pointcut()")
	public Object around(ProceedingJoinPoint jp) throws Throwable{
		String targetName = jp.getTarget().getClass().getName();// 真实类名字
		String methodName = jp.getSignature().getName();// 真实方式
		Object[] arguments = jp.getArgs();// 所有请求参数
		Object[] args = new Object[arguments.length];
		Object ret = null;
		try {
			jp.proceed();
		} catch (EsellException e){
			ret = ApiResponse.error(PssUtil.errorCode(((EsellException)e).getMessage()));
		} catch (Exception e) {
			log.error(StrUtil.format("统一异常处理 className:{} methodName:{} exception:"
				,className,methodName),e);
			ret = ApiResponse.error(Code.SYS_SERVICE_ERROR);
		}
		return ret;
	}
}

第二步:测试接口例子

@RequestMapping("test/aop.shtm")
public ApiResponse testAop(@RequestParameter SimpleApiRequest apiRequest){
   Integer a = apiRequest.getInteger("a");
   PssUtil.check(2 == a,"a的值不能为2");
   Integer b = a/0;
   return ApiResponse.OK;
}

第三部:去查看效果吧

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AleneFv

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值