springboot 参数异常拦截(3种)

参数异常处理策略
本文介绍了一种针对HTTP请求中参数异常的处理策略,包括不同类型的参数校验异常及其处理方式,如MethodArgumentNotValidException、ConstraintViolationException和BindException等。
    /** 
     * 参数异常拦截 (model 里面的)
     * @author 
     * @date 2020/11/17 0017
     * @param  e
     * @return GenericResponse
     **/
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GenericResponse methodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder builder = new StringBuilder();
        for (ObjectError allError : allErrors) {
            String message = allError.getDefaultMessage();
            builder.append(message);
        }
        log.error("接口:" + request.getServletPath(), builder.toString());
        return GenericResponse.response(false, 1000, builder.toString());
    }

    /**
     * 参数异常拦截 (方法上的)
     * @author 
     * @date 2020/11/17 0017
     * @param  e
     * @return GenericResponse
     **/
    @ExceptionHandler(ConstraintViolationException.class)
    public GenericResponse constraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        StringBuilder builder = new StringBuilder();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            String message = constraintViolation.getMessage();
            builder.append(message);
        }
        log.error("接口:" + request.getServletPath(), e.toString());
        return GenericResponse.response(false, 1000, builder.toString());
    }

    /**
     * @GetMapping("test")
     *       public GenericResponse test(@Valid AuthRoleMenu authRoleMenu) {
     *            return null;
     *      }
     * 参数异常拦截(Get请求 ?拼接形式)
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    public GenericResponse bindException(BindException e, HttpServletRequest request) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder builder = new StringBuilder();
        for (ObjectError allError : allErrors) {
            String message = allError.getDefaultMessage();
            builder.append(message);
        }
        log.error("接口:" + request.getServletPath(), builder.toString());
        return GenericResponse.response(false, 1000, builder.toString());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢了尾巴的猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值