spring boot之注解校验 valid和validated

ctrl:

 @PostMapping("getVerificationCodeByPhone")
    @ResponseBody
    public R getVerificationCodeByPhone(@ApiParam(value = "传入手机号和有效时长获取短信验证码", name = "vo", required = true) @Valid @RequestBody VerifyCodeVo vo
//            , BindingResult bindingResult)  {
    )  {
        R result = null;
        try {
            result = commonService.getVerificationCodeByPhone(vo);
        } catch (Exception e) {
            logger.error("获取短信验证码 异常:{}", e.toString());
            Map<String, String> map = new HashMap<>();
            map.put("exception", e.toString());
            result = R.exception("系统异常", map);
        }

        return result;
    }

dto:

@Data
@ApiModel(value = "验证码视图")
public class VerifyCodeVo implements Serializable {

    @ApiModelProperty(value = "电话号码")
    @Pattern(regexp = "1[3|4|5|7|8][0-9]\\d{8}",message = "手机号格式错误")
    @NotNull(message = "手机号不能为空")
    private String mobile;
    @ApiModelProperty(value = "验证码有效时长,单位:秒(一般:1-5分钟)",example = "120")
    @Min(value = 0,message = "有效时长不能小于0分钟")
    @Max(value = 300,message = "有效时长不能大于5分钟")
    private Long effectiveDuration;
}

统一异常处理类:

@ControllerAdvice()
public class ExceptionControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionControllerAdvice.class);

    /**
     *  校验错误拦截处理
     *对方法参数校验异常处理方法(前端提交的方式为json格式出现异常时会被该异常类处理)
     * json格式提交时,spring会采用json数据的数据转换器进行处理(进行参数校验时错误是抛出MethodArgumentNotValidException异常)
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public R validationBodyException(MethodArgumentNotValidException exception){

        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> hashMap = new HashMap<>();
            List<ObjectError> errors = result.getAllErrors();

            errors.forEach(p ->{
                FieldError fieldError = (FieldError) p;
                logger.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
                hashMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            });

            return R.exception("未知异常",hashMap);
        }
        return R.ok(" 解析异常,包装成想要的数据,就可以返回到前台了");
    }

    /**
     * 对方法参数校验异常处理方法(仅对于表单提交有效,对于以json格式提交将会失效)
     * 如果是表单类型的提交,则spring会采用表单数据的处理类进行处理(进行参数校验错误时会抛出BindException异常)
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R bindExceptionHandler(BindException ex){
        // ...
        logger.info(ex.toString());
        // ...
        return R.ok(" 解析这个异常,然后包装成你想要的数据,就可以返回到前台了");
    }
    /**
     * 参数类型转换错误
     *
     * @param exception 错误
     * @return 错误信息
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    @ResponseBody
    public R parameterTypeException(HttpMessageConversionException exception){

        logger.error(exception.getCause().getLocalizedMessage());
        return R.error("类型转换错误");

    }

    /**
     * 全局异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception ex){
        // ...
        logger.error(ex.toString());
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put(ex.getClass().getName(),ex.getMessage());
        // ...
        return R.exception("未知异常",hashMap);
    }
}

统一异常处理:

当注解校验为:@valid时,请求方式中的content-type为 json:@RequestBody 时, 然后在校验对象 参数后面加上 BindingResult对象。如:@Valid @RequestBody VerifyCodeVo vo  , BindingResult bindingResult 并在该方法中进行异常处理。

当注解校验为:@valid时,请求方式中的content-type为 json:@RequestBody 时,通过统一异常处理类处理该异常。如:@Valid @RequestBody VerifyCodeVo vo  并在validationBodyException方法中进行异常处理。

 

当注解校验为:@validated时,表单类型的提交: 然后在校验对象 参数后面加上 BindingResult对象。如:@Validated @RequestBody VerifyCodeVo vo  , BindingResult bindingResult 并在该方法中进行异常处理。

当注解校验为:@validated时,表单类型的提交: 然后  通过统一异常处理类处理该异常。如:@Validated @RequestBody VerifyCodeVo vo   并在bindExceptionHandler方法中进行异常处理。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值