SpringBoot

Bean Validation参数校验异常处理器

2021-08-05  本文已影响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,"请求参数校验错误");
    }

}
上一篇 下一篇

猜你喜欢

热点阅读