美文网首页SpringBoot
Bean Validation参数校验异常处理器

Bean Validation参数校验异常处理器

作者: 星钻首席小管家 | 来源:发表于2021-08-05 16:56 被阅读0次

1.在实体类属性上加注解

public class RichTextSendManyDTO {
    private String id;
    @Length(max = 64,message = "标题长度不能超过64")
    private String title;
    private String openId;
}

2.在请求方法上加注解@Valid

public JsonResult sendMany(@Valid @RequestBody RichTextSendManyDTO dto){
        return richTextService.sendMany(dto,"");
    }

3.统一异常处理类

@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class MyExceptionHander {

    /**
     * Bean Validation参数校验异常处理器
     * @param e 参数验证异常
     * @return ResultObject
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public JsonResult parameterExceptionHandler(MethodArgumentNotValidException e) {
        int errCode = 1006;
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 这里列出了全部错误参数,这里用List传回
        List<ObjectError> errors = exceptions.getAllErrors();
        // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
        if(ObjectUtils.isNotEmpty(errors)){
            return new JsonResult(errCode, errors.get(0).getDefaultMessage());
        }
        return new JsonResult(errCode,"请求参数校验错误");
    }

}

相关文章

网友评论

    本文标题:Bean Validation参数校验异常处理器

    本文链接:https://www.haomeiwen.com/subject/dvomvltx.html