@ControllerAdvice spring MVC与spring boot 拦截区别

@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才可以拦截

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值