现象: 如果自定义异常是编译时异常,那么在使用aop时抛出的是UndeclaredThrowableException,底层caused by是由自定义异常引起的。而不是自定义的异常。
解决办法:修改方式有很多,可以在全局异常处理中捕获该异常,调用该异常的getCause()方法就可以拿到自定义异常,再将自定义异常抛出,如下:
/**
* 拦截器校验异常(防止AOP将自定义异常转换成UndeclaredThrowableException)
* CustomException:自定义异常
* @param
* @return
*/
@ExceptionHandler(UndeclaredThrowableException.class)
@ResponseBody
public TransportResponse aopException(UndeclaredThrowableException invocationTargetException) {
if (invocationTargetException.getCause() instanceof CustomException) {
CustomException e = (CustomException) invocationTargetException.getCause();
logger.error("发生异常!原因是:{}", invocationTargetException);
//重点
return new TransportResponse(e.getErrorCode(), e.getErrorMsg(), null);
}
logger.error("未知异常,原因是:", invocationTargetException);
return new TransportResponse(StatusCode.EXCEPTION, null);
}