问题
使用spring Aop 验证用户是否有权限,如果没有则抛出自定义异常,在调用统一异常类处理
代码如下:
AOP切面类:
@Aspect
@Component
public class CheckPermissionAspectAop {
private static final Logger logger = LoggerFactory.getLogger(CheckPermissionAspectAop.class);
//切入点为 @CheckPermission注解的方法
@Pointcut("@annotation(checkPermission)")
public void joinPointExpression(CheckPermission checkPermission){}
/**
* 在方法执行之前进行权限检查
* @param joinpoint
* @throws Exception
*/
@Before("joinPointExpression(checkPermission)")
public void beforeMethod(JoinPoint joinpoint,CheckPermission checkPermission) throws Exception {
logger.info("<========check permission start============>");
//具体逻辑 start
boolean accessFlag = false;
if(!accessFlag) {
//CheckPermissionException 自定义异常
throw new CheckPermissionException("没有权限", 511);
}
//具体逻辑 end
logger.info("<========check permission end============>");
}
}
自定义异常类:
public class CheckPermissionException extends Exception{
public int code = BaseResponse.ERROR_RESULT.getResponseCode();
public CheckPermissionException () {
super();
}
public CheckPermissionException (int code) {
super();
this.code = code;
}
public CheckPermissionException (String message, int code) {
super(message);
this.code = code;
}
}
异常统一处理类
@ControllerAdvice @ResponseBody public class ExceptionAdvice{ /** * 500 - Internal Server Error */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) public GenericResp<T> handleException(BossException e) { GenericResp<T> returnVo = new GenericResp<>(); returnVo.setCode(e.getCode()); returnVo.setMessage(e.getMessage()); return returnVo; } }
使用没有权限的用户调用接口抛出异常
{timestamp: 15526589711, status:500, error: "Internal Server Error",...}
error: "Internal Server Error"
exception :"java.lang.reflect.UndeclaredThrowableException"
message: "org.springframework.web.util.NestedServletException: Request processing...."
path : "/test/api/create"
status : 500
并没有抛出自定义异常
{code:500, message: "没有权限" ,data:null}
网上搜索 异常处理类是动态代理的一个实现。
如果一个异常是检查型异常并且没有在动态代理的接口处声明,那么它将会被包装成UndeclaredThrowableException.
而我们定义的自定义异常,被定义成了检查型异常,导致被包装成了UndeclaredThrowableException
解决方法:
自定义异常为 运行时异常即可
修改自定义异常类:
public class CheckPermissionException extends RuntimeException {
public int code = BaseResponse.ERROR_RESULT.getResponseCode();
public CheckPermissionException () {
super();
}
public CheckPermissionException (int code) {
super();
this.code = code;
}
public CheckPermissionException (String message, int code) {
super(message);
this.code = code;
}
}