zoukankan      html  css  js  c++  java
  • 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"); }
  • 相关阅读:
    [转]Go语言中的make和new
    Python中的get和set方法
    协程是个啥玩意
    聊聊Python中的is和==
    聊聊Python中的闭包和装饰器
    聊聊Python中的生成器和迭代器
    聊聊动态语言那些事(Python)
    在mac上安装svn客户端
    关于mac mini组装普液晶显示器
    IOS 日志输出控制
  • 原文地址:https://www.cnblogs.com/zjm-1/p/12207019.html
Copyright © 2011-2022 走看看