第一步:定义切面类
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;
}
第三部:去查看效果吧