Java Code Examples for org.springframework.validation.BindingResult#getFieldErrors()

The following examples show how to use org.springframework.validation.BindingResult#getFieldErrors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CheckUtil.java    From layui-admin with MIT License 6 votes vote down vote up
/**
 * 校验model上的注解
 *
 * @param pjp 连接点
 */
public static void checkModel(ProceedingJoinPoint pjp) {
    StringBuilder sb = new StringBuilder();
    try {
        //找到BindingResult参数
        List<BindingResult> results = getBindingResult(pjp);
        if (results != null && !results.isEmpty()) {
            for (BindingResult result : results) {
                if (null != result && result.hasErrors()) {
                    //拼接错误信息
                    if (null != result.getFieldErrors()) {
                        for (FieldError fe : result.getFieldErrors()) {
                            sb.append(fe.getField() + "-" + fe.getDefaultMessage()).append(" ");
                        }
                    }
                }
            }

            if (StringUtils.isNotBlank(sb.toString())) {
                fail(sb.toString());//抛出检查异常
            }
        }
    } catch (Exception e) {
        fail(e.getMessage());//抛出检查异常
    }
}
 
Example 2
Source File: JsonResult.java    From match-trade with Apache License 2.0 6 votes vote down vote up
/**
 * <p>返回失败,无数据</p>
 * @param BindingResult
 * @return JsonResult
 */
public JsonResult<T> error(BindingResult result, MessageSource messageSource) {
    StringBuffer msg = new StringBuffer();
    // 获取错位字段集合
    List<FieldError> fieldErrors = result.getFieldErrors();
    // 获取本地locale,zh_CN
    Locale currentLocale = LocaleContextHolder.getLocale();
    for (FieldError fieldError : fieldErrors) {
        // 获取错误信息
        String errorMessage = messageSource.getMessage(fieldError, currentLocale);
        // 添加到错误消息集合内
        msg.append(fieldError.getField() + ":" + errorMessage + " ");
    }
    this.setCode(CODE_FAILED);
    this.setMsg(msg.toString());
    this.setData(null);
    return this;
}
 
Example 3
Source File: Tools.java    From mcg-helper with Apache License 2.0 6 votes vote down vote up
public static boolean validator(BindingResult result, McgResult mcgResult, NotifyBody notifyBody) {
    boolean flag = false;
       
       if(result.getFieldErrorCount() > 0) {
           StringBuilder sb = new StringBuilder();
           for(FieldError fieldError : result.getFieldErrors()) {
               sb.append(fieldError.getDefaultMessage() + ",");
           }
           sb.deleteCharAt(sb.length()-1);
           mcgResult.setStatusCode(0);
           notifyBody.setContent(sb.toString());
           notifyBody.setType(LogTypeEnum.ERROR.getValue());
       } else {
           flag = true;
       }
       
       return flag;
}
 
Example 4
Source File: SpringExceptionHandler.java    From market with MIT License 5 votes vote down vote up
/**
 * Ошибки валидации полученного от клиента объекта.
 * Ответ сервера сопровождается пояснениями.
 *
 * @return перечень нарушенных ограничений
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
	BindingResult result = ex.getBindingResult();
	List<FieldError> fieldErrors = result.getFieldErrors();

	return processFieldErrors(fieldErrors);
}
 
Example 5
Source File: BaseController.java    From wingcloud with Apache License 2.0 5 votes vote down vote up
/**
 * 接口输入参数合法性校验
 *
 * @param result
 */
protected void validate(BindingResult result){
    if(result.hasFieldErrors()){
        List<FieldError> errorList = result.getFieldErrors();
        errorList.stream().forEach(item -> Assert.isTrue(false,item.getDefaultMessage()));
    }
}
 
Example 6
Source File: ExceptionTranslator.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
 
Example 7
Source File: ExceptionTranslator.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
 
Example 8
Source File: ExceptionTranslator.java    From tutorials with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
 
Example 9
Source File: ThrowableUtils.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * 校验参数正确,拼装字段名和值到错误信息
 * @param result
 */
public static void checkParamArgument(BindingResult result) {
    if (result != null && result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> errors = result.getFieldErrors();
        if(CollectionUtil.isNotEmpty(errors)){
            FieldError error = errors.get(0);
            String rejectedValue = Objects.toString(error.getRejectedValue(), "");
            String defMsg = error.getDefaultMessage();
            // 排除类上面的注解提示
            if(rejectedValue.contains(Constants.DELIMITER_TO)){
                // 自己去确定错误字段
                sb.append(defMsg);
            }else{
                if(Constants.DELIMITER_COLON.contains(defMsg)){
                    sb.append(error.getField()).append(" ").append(defMsg);
                }else{
                    sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue);
                }
            }
        } else {
            String msg = result.getAllErrors().get(0).getDefaultMessage();
            sb.append(msg);
        }
        throw new ApiInvalidParamException(sb.toString());
    }
}
 
Example 10
Source File: RestExceptionHandler.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * validation 异常处理
 *
 * @param request 请求体
 * @param e       MethodArgumentNotValidException
 * @return HttpResult
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Result onMethodArgumentNotValidException(HttpServletRequest request,
                                                MethodArgumentNotValidException e) {
    BindingResult result = e.getBindingResult();
    if (result != null && result.hasErrors()) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> errors = result.getFieldErrors();
        if(CollectionUtil.isNotEmpty(errors)){
            FieldError error = errors.get(0);
            String rejectedValue = Objects.toString(error.getRejectedValue(), "");
            String defMsg = error.getDefaultMessage();
            // 排除类上面的注解提示
            if(rejectedValue.contains(Constants.DELIMITER_TO)){
                // 自己去确定错误字段
                sb.append(defMsg);
            }else{
                if(Constants.DELIMITER_COLON.contains(defMsg)){
                    sb.append(error.getField()).append(" ").append(defMsg);
                }else{
                    sb.append(error.getField()).append(" ").append(defMsg).append(":").append(rejectedValue);
                }
            }
        } else {
            String msg = result.getAllErrors().get(0).getDefaultMessage();
            sb.append(msg);
        }

        return Result.createWithErrorMessage(sb.toString(), ErrorEnum.PARAM_ERROR.getCode());
    }

    return null;
}
 
Example 11
Source File: ExceptionTranslator.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();
    ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION);
    for (FieldError fieldError : fieldErrors) {
        dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode());
    }
    return dto;
}
 
Example 12
Source File: ExceptionTranslator.java    From tutorials with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
 
Example 13
Source File: FooController.java    From code with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/live")
public String live(@Validated Foo foo, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            //...
        }
        return "fail";
    }
    return "success";
}
 
Example 14
Source File: ValidationUtil.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static List<FormErrorRepresentation> extractFormErrors(BindingResult result) {
    List<FormErrorRepresentation> formErrors = new ArrayList<>();
    for (FieldError fieldError : result.getFieldErrors()) {
        formErrors.add(new FormErrorRepresentation(fieldError));
    }
    return formErrors;
}
 
Example 15
Source File: CustomGlobalExceptionHandler.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 提取Validator产生的异常错误
 *
 * @param bindingResult bindingResult
 * @return Exception
 */
private Exception parseBindingResult(BindingResult bindingResult) {
    Map<String, String> errorMsgs = new HashMap<>();
    for (FieldError error : bindingResult.getFieldErrors()) {
        errorMsgs.put(error.getField(), error.getDefaultMessage());
    }
    if (errorMsgs.isEmpty()) {
        return new CommonException(ApiMsg.KEY_PARAM_VALIDATE + "");
    } else {
        return new CommonException(JsonMapper.toJsonString(errorMsgs));
    }
}
 
Example 16
Source File: BindingResultSerializer.java    From springlets with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(BindingResult result, JsonGenerator jgen, SerializerProvider provider)
    throws IOException, JsonProcessingException {

  // Create the errors map
  Map<String, Object> allErrorsMessages = new HashMap<String, Object>();

  // Get field errors
  List<FieldError> fieldErrors = result.getFieldErrors();
  if (fieldErrors.isEmpty()) {
    // Nothing to do
    jgen.writeNull();
    return;
  }

  // Check if target type is an array or a bean
  @SuppressWarnings("rawtypes")
  Class targetClass = result.getTarget().getClass();
  if (targetClass.isArray() || Collection.class.isAssignableFrom(targetClass)) {
    loadListErrors(result.getFieldErrors(), allErrorsMessages);
  } else {
    loadObjectErrors(result.getFieldErrors(), allErrorsMessages);
  }

  // Create the result map
  Map<String, Object> bindingResult = new HashMap<String, Object>();
  bindingResult.put("target-resource", StringUtils.uncapitalize(result.getObjectName()));
  bindingResult.put("error-count", result.getErrorCount());
  bindingResult.put("errors", allErrorsMessages);

  jgen.writeObject(bindingResult);
}
 
Example 17
Source File: ExceptionTranslator.java    From flair-registry with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();
    ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION);
    for (FieldError fieldError : fieldErrors) {
        dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode());
    }
    return dto;
}
 
Example 18
Source File: ExceptionTranslator.java    From OpenIoE with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
 
Example 19
Source File: ValidExceptionHandler.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 5 votes vote down vote up
/**
 * 异常信息
 *
 * @param result
 * @return
 */
private String extractErrorMsg(BindingResult result) {
    List<FieldError> errors = result.getFieldErrors();

    return errors.stream().map(e -> e.getField()+ ":" + e.getDefaultMessage())
            .reduce((s1, s2) -> s1 + " ; " +s2).orElseGet( ()->"参数非法");
}
 
Example 20
Source File: GlobalExceptionHandler.java    From EosProxyServer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@ExceptionHandler
@ResponseStatus
public ResponseEntity<MessageResult> hadleServerException(Exception exception) {

    //默认打印错误,并且返回server error
    exception.printStackTrace();
    HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    Integer code = ErrorCodeEnumChain.unknown_error_exception.getMsg_id();
    String msg = ErrorCodeEnumChain.getMsgById(code);

    //不支持的method
    if(exception instanceof HttpRequestMethodNotSupportedException) {
        httpStatus = HttpStatus.NOT_FOUND;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    //没有handler
    else if (exception instanceof NoHandlerFoundException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    //缺失parameter
    else if (exception instanceof MissingServletRequestParameterException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if (exception instanceof RedisConnectionException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.redis_connection_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if(exception instanceof MethodArgumentTypeMismatchException){
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.request_format_exception.getMsg_id();
        msg = exception.getMessage();
    }
    else if(exception instanceof MethodArgumentNotValidException){
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.request_format_exception.getMsg_id();
        BindingResult bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        msg = "parameter validate error:";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            msg += fieldError.getDefaultMessage() + ", ";
        }
    }
    log.warn("X--->{code:" + code + ",msg:" + msg + ",what:" + exception.getMessage());
    return new ResponseEntity(new MessageResult(msg, code, exception.getMessage()), httpStatus);
}