@ControllerAdvice注解是用来做异常拦截处理,我在spring boot和spring mvc中都使用过,两个都是在切面抛出异常。
异常拦截类
/**
* 全局异常处理器
*/
@ControllerAdvice
public class GlobalExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionResolver.class);
/**
* 处理所有业务异常
*
* @param e 业务异常
* @return json结果
*/
@ExceptionHandler(APIBusinessException.class)
@ResponseBody
public ApiResult handleOpdRuntimeException(APIBusinessException e) {
// 不打印异常堆栈信息
LOG.error(e.getMsg());
return new ApiResult(e.getState(),e.getMsg());
}
}
spring boot项目
切面代码
@Aspect
@Component
public class OauthAspect {
@Before("@annotation(com.signverify.annotation.CustomOauth)))")
public void connectOauth(JoinPoint joinPoint) throws APIBusinessException {
throw new APIBusinessException(ResultCode.NO_PERMISSION);
}
}
spring mvc项目
@Aspect
@Controller
public class OauthAspect {
@Before("@annotation(com.signverify.annotation.CustomOauth)))")
public void connectOauth(JoinPoint joinPoint) throws APIBusinessException {
throw new APIBusinessException(ResultCode.NO_PERMISSION);
}
}
在spring boot项目中,只需要在切面上加上注解@Component就可以拦截到异常,spring mvc项目必须是将切面注解为Controller才可以拦截