spring boot的数据校验,通过全局异常处理
Posted 玉龙小主
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot的数据校验,通过全局异常处理相关的知识,希望对你有一定的参考价值。
//2019/8/10 zjm
@ControllerAdvice public class ExceptionController { private final static Logger logger = LoggerFactory.getLogger(ExceptionController.class); @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public FrontResponse validationBodyException(MethodArgumentNotValidException exception){ BindingResult bindingResult = exception.getBindingResult(); return getBindingResult(bindingResult); } @ExceptionHandler(value = BindException.class) @ResponseBody public FrontResponse validationBindException(BindException exception){ BindingResult bindingResult = exception.getBindingResult(); return getBindingResult(bindingResult); } private FrontResponse getBindingResult(BindingResult bindingResult){ List<ObjectError> list = bindingResult.getAllErrors(); StringBuilder builder = new StringBuilder(); list.forEach(x -> { FieldError error = (FieldError) x; builder.append(error.getDefaultMessage()); builder.append("<br/>"); } ); return FrontResponse.fail(ErrorCodeDict.PARAMETER_INVALID.getCode(),builder.toString()); } @ExceptionHandler(value = ConstraintViolationException.class) @ResponseBody public FrontResponse ConstraintViolationExceptionHandler(ConstraintViolationException exception) { Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); StringBuilder builder = new StringBuilder(); for (ConstraintViolation<?> item : violations) { builder.append(item.getMessage()); builder.append("<br/>"); } return FrontResponse.fail(ErrorCodeDict.PARAMETER_INVALID.getCode(),builder.toString()); } @ExceptionHandler(value = HttpMessageConversionException.class) @ResponseBody public FrontResponse parameterTypeException(HttpMessageConversionException exception){ return FrontResponse.fail(ErrorCodeDict.PARAMETER_INVALID.getCode(),"parameterTypeException"); } @ExceptionHandler(value = Exception.class) @ResponseBody public FrontResponse handle(Exception e) { logger.error("系统异常", e); return FrontResponse.fail(ErrorCodeDict.SYSTEM_ERROR.getCode(),"system error"); }
以上是关于spring boot的数据校验,通过全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章
SpringMvc,Springboot统一校验自定义异常全局异常处理