org.springframework.validation.BindingResult.getFieldErrors()

Here are the examples of the java api org.springframework.validation.BindingResult.getFieldErrors() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

107 Examples 7

19 View Source File : ValidExceptionHandler.java
License : Apache License 2.0
Project Creator : xwjie

/**
 * 异常信息
 *
 * @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(() -> "参数非法");
}

19 View Source File : UserApi.java
License : MIT License
Project Creator : wangyuheng

@GetMapping("/{uid}")
public Object getInfo(@Validated User user, BindingResult bindingResult) {
    Map<String, Object> result = new HashMap<>();
    if (bindingResult.hasErrors()) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Locale locale = LocaleContextHolder.getLocale();
        StringBuilder errorMessage = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            errorMessage.append(fieldError.getField()).append(":").append(messageSource.getMessage(fieldError, locale)).append(",");
        });
        result.put("code", 10001);
        result.put("message", errorMessage);
    } else {
        result.put("code", 10000);
        result.put("data", user);
    }
    return result;
}

19 View Source File : ResponseEntity.java
License : GNU General Public License v3.0
Project Creator : silently9527

public static ResponseEnreplacedy failure(BindingResult result) {
    ResponseEnreplacedy responseEnreplacedy = new ResponseEnreplacedy();
    StringBuilder message = new StringBuilder();
    final List<FieldError> fieldErrors = result.getFieldErrors();
    for (FieldError fieldError : fieldErrors) {
        final String defaultMessage = fieldError.getDefaultMessage();
        message.append(defaultMessage).append(";");
    }
    if (message.length() > 0) {
        message.deleteCharAt(message.length() - 1);
    }
    responseEnreplacedy.put(SUCCESSFUL_KEY, false);
    responseEnreplacedy.put(RESPONSE_CODE_KEY, HttpStatus.SERVICE_UNAVAILABLE.value());
    responseEnreplacedy.put(MESSAGE_KEY, message);
    return responseEnreplacedy;
}

19 View Source File : FormRestResponse.java
License : Mozilla Public License 2.0
Project Creator : secdec

public static <T> FormRestResponse<T> failure(String response, BindingResult result, Map<String, String> errors) {
    FormRestResponse<T> restResponse = new FormRestResponse<T>();
    Map<String, String> resultMap = map();
    resultMap.putAll(errors);
    if (result != null) {
        if (result.getFieldErrors() != null && result.getFieldErrors().size() > 0) {
            resultMap = map();
            for (FieldError error : result.getFieldErrors()) {
                String value = getErrorMessage(error);
                String field = error.getField().replace(".", "_");
                resultMap.put(field, value);
            }
        }
    }
    restResponse.errorMap = resultMap;
    restResponse.message = response;
    return restResponse;
}

19 View Source File : MyValidator.java
License : MIT License
Project Creator : netyjq

/**
 * 验证前端参数,有错误直接抛出异常
 * @param result BindResult
 * @throws ParamInvalidException  参数异常
 * @return
 */
public static void validateBindResult(BindingResult result) throws ParamInvalidException {
    if (result != null && result.hasErrors()) {
        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            throw new ParamInvalidException(error.getField(), error.getDefaultMessage());
        }
    }
}

19 View Source File : ExceptionTranslator.java
License : MIT License
Project Creator : luban-h5

@Override
public ErrorVM getErrorVM(BindingResult bindingResult) {
    BindingResult result = bindingResult;
    List<FieldError> fieldErrors = result.getFieldErrors();
    List<FieldVM> fieldVMS = new ArrayList(fieldErrors.size());
    for (FieldError fieldError : fieldErrors) {
        String objectName = fieldError.getObjectName();
        String field = fieldError.getField();
        String defaultMessage = fieldError.getDefaultMessage();
        String code = fieldError.getCode();
        fieldVMS.add(new FieldVM(objectName, field, code, defaultMessage, null));
    }
    if (!CollectionUtils.isEmpty(fieldErrors)) {
        String errorCode = fieldErrors.get(0).getCode();
        String message = fieldErrors.get(0).getDefaultMessage();
        return new ErrorVM(errorCode, message, null, HttpStatus.BAD_REQUEST.value(), fieldVMS);
    }
    String errorCode = ErrorEnum.METHOD_ARGUMENT_NOT_VALID.getError();
    return new ErrorVM(errorCode, ErrorEnum.METHOD_ARGUMENT_NOT_VALID.getDesc(), null, HttpStatus.BAD_REQUEST.value(), fieldVMS);
}

19 View Source File : PassjavaExceptionControllerAdvice.java
License : Apache License 2.0
Project Creator : Jackson0714

@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.clreplaced)
public R handleValidException(MethodArgumentNotValidException e) {
    // log.error("数据校验出现问题{},异常类型:{}", e.getMessage(), e.getClreplaced());
    BindingResult bindingResult = e.getBindingResult();
    Map<String, String> errorMap = new HashMap<>();
    bindingResult.getFieldErrors().forEach((fieldError) -> {
        errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
    });
    return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
}

19 View Source File : ControllerUtils.java
License : GNU General Public License v3.0
Project Creator : ivan909020

public static Map<String, String> findErrors(BindingResult bindingResult) {
    Collector<FieldError, ?, Map<String, String>> collector = Collectors.toMap(fieldError -> fieldError.getField() + "Error", FieldError::getDefaultMessage);
    return bindingResult.getFieldErrors().stream().collect(collector);
}

19 View Source File : BindingResultFormat.java
License : GNU General Public License v3.0
Project Creator : hackyoMa

/**
 * 格式化参数校验结果
 *
 * @param bindingResult bindingResult
 * @return 参数校验结果
 */
public static Map<String, String> format(BindingResult bindingResult) {
    List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
    Map<String, String> fieldErrorMap = new HashMap<>(fieldErrorList.size());
    for (FieldError fieldError : fieldErrorList) {
        fieldErrorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
    }
    return fieldErrorMap;
}

19 View Source File : BindingResultErrorUtils.java
License : Apache License 2.0
Project Creator : faster-framework

/**
 * @param bindingResult bindingResult
 * @return bindingResult错误内容
 */
public static String resolveErrorMessage(BindingResult bindingResult) {
    if (bindingResult == null || CollectionUtils.isEmpty(bindingResult.getFieldErrors())) {
        return "";
    }
    StringBuilder errorMsg = new StringBuilder();
    List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
    for (FieldError fieldError : fieldErrorList) {
        errorMsg.append("[").append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("]");
    }
    return errorMsg.toString();
}

19 View Source File : ValidationUtils.java
License : Apache License 2.0
Project Creator : EdurtIO

/**
 * get error information
 *
 * @param result error information
 * @return error list
 */
public static Map<String, Object> extractValidate(BindingResult result) {
    Map<String, Object> error = new ConcurrentHashMap<>();
    List<FieldError> allErrors = result.getFieldErrors();
    error.put("count", allErrors.size());
    List<Map<String, Object>> fields = new ArrayList<>();
    allErrors.forEach(v -> {
        Map<String, Object> field = new ConcurrentHashMap<>();
        field.put("field", v.getField());
        field.put("message", checkException(v.getDefaultMessage()));
        fields.add(field);
    });
    error.put("error", fields);
    return error;
}

19 View Source File : CmnUtils.java
License : MIT License
Project Creator : akageun

/**
 * @Valid 에서 출력된 메시지를 가져옴.
 *
 * @param result
 * @param seperator
 * @return
 */
public static String getErrMsg(BindingResult result, char seperator) {
    if (result.hasErrors() == false) {
        // 오사용으로 인한 방어처리
        return "";
    }
    List<FieldError> errors = result.getFieldErrors();
    StringBuilder message = new StringBuilder();
    int errSize = errors.size();
    for (int i = 0; i < errSize; i++) {
        if (StringUtils.equals(errors.get(i).getCode(), "typeMismatch")) {
            message.append(errors.get(i).getField());
            message.append(" is type Mismatch");
        } else {
            message.append(errors.get(i).getDefaultMessage());
        }
        if (i != errSize - 1) {
            message.append(seperator);
        }
    }
    return message.toString();
}

19 View Source File : ParamsValidateAspect.java
License : Apache License 2.0
Project Creator : 734839030

@Around("anyMethod() && args(..)")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Object[] args = point.getArgs();
    if (null != args && args.length > 0) {
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult br = (BindingResult) arg;
                if (br.hasErrors()) {
                    FieldError fieldError = br.getFieldErrors().get(0);
                    throw new ResponeException(ExceptionCode.PARAM_INVALID, "参数校验错误", new Object[] { fieldError.getField(), fieldError.getDefaultMessage() });
                }
            }
        }
    }
    return point.proceed();
}

19 View Source File : JsonResult.java
License : Apache License 2.0
Project Creator : 171906502

/**
 * <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;
}

18 View Source File : BindingErrorsResponse.java
License : Apache License 2.0
Project Creator : spring-petclinic

public void addAllErrors(BindingResult bindingResult) {
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        BindingError error = new BindingError();
        error.setObjectName(fieldError.getObjectName());
        error.setFieldName(fieldError.getField());
        error.setFieldValue(String.valueOf(fieldError.getRejectedValue()));
        error.setErrorMessage(fieldError.getDefaultMessage());
        addError(error);
    }
}

18 View Source File : GlobalExceptionHandler.java
License : GNU Lesser General Public License v3.0
Project Creator : OracleChain

// 其他异常
@ExceptionHandler
@ResponseStatus
public ResponseEnreplacedy<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();
    } else // 没有handler
    if (exception instanceof NoHandlerFoundException) {
        httpStatus = HttpStatus.BAD_REQUEST;
        code = ErrorCodeEnumChain.not_supported_exception.getMsg_id();
        msg = exception.getMessage();
    } else // 缺失parameter
    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 ResponseEnreplacedy(new MessageResult(msg, code, exception.getMessage()), httpStatus);
}

@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@ResponseBody
public Error handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<String> errorList = new ArrayList<>();
    result.getFieldErrors().forEach((fieldError) -> {
        errorList.add(fieldError.getDefaultMessage());
    });
    result.getGlobalErrors().forEach((fieldError) -> {
        errorList.add(fieldError.getObjectName() + " : " + fieldError.getDefaultMessage());
    });
    return new Error(HttpStatus.BAD_REQUEST, ex.getMessage(), errorList);
}

18 View Source File : ErrorHandlerServiceImpl.java
License : GNU General Public License v3.0
Project Creator : ManaZeak

/**
 * {@inheritDoc}
 */
@Override
public void handleValidationErrors(BindingResult result) {
    // Checking if there is some validation errors.
    if (!result.hasErrors()) {
        return;
    }
    generateRestErrorFromValidationError(result.getFieldErrors());
}

18 View Source File : BaseController.java
License : MIT License
Project Creator : lynnlovemin

/**
 * 参数的合法性校验
 * @param result
 */
protected void validate(BindingResult result) {
    if (result.hasFieldErrors()) {
        List<FieldError> errorList = result.getFieldErrors();
        errorList.stream().forEach(item -> replacedert.isTrue(false, item.getDefaultMessage()));
    }
}

18 View Source File : ValidationMessages.java
License : MIT License
Project Creator : InnovateUKGitHub

private void populateFromBindingResult(Long objectId, BindingResult bindingResult) {
    List<Error> fieldErrors = simpleMap(bindingResult.getFieldErrors(), e -> fieldError(e.getField(), e.getRejectedValue(), getErrorKeyFromBindingError(e), getArgumentsFromBindingError(e)));
    List<Error> globalErrors = simpleMap(bindingResult.getGlobalErrors(), e -> globalError(getErrorKeyFromBindingError(e), getArgumentsFromBindingError(e)));
    errors.addAll(combineLists(fieldErrors, globalErrors));
    objectName = bindingResult.getObjectName();
    this.objectId = objectId;
}

18 View Source File : GlobalExceptionHandler.java
License : Apache License 2.0
Project Creator : hdonghong

/**
 * 出现参数校验异常
 * @param e 异常
 * @return 通用result
 */
@ExceptionHandler(value = { BindException.clreplaced, MethodArgumentNotValidException.clreplaced })
public ResultVO<?> handleBindException(Exception e) {
    BindingResult bindingResult = BindException.clreplaced.isInstance(e) ? ((BindException) e).getBindingResult() : ((MethodArgumentNotValidException) e).getBindingResult();
    Object[] messageArr = bindingResult.getFieldErrors().stream().map(error -> error.getField() + error.getDefaultMessage()).toArray();
    return Result.error(CodeMsgEnum.PARAMETER_ERROR).appendArgs(messageArr);
}

18 View Source File : CheckUtil.java
License : MIT License
Project Creator : gameloft9

/**
 * 校验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());
    }
}

18 View Source File : ParameterInvalidItemHelper.java
License : GNU Lesser General Public License v2.1
Project Creator : fanhualei

public static List<ParameterInvalidItem> convertBindingResultToMapParameterInvalidItemList(BindingResult bindingResult) {
    if (bindingResult == null) {
        return null;
    }
    List<ParameterInvalidItem> parameterInvalidItemList = Lists.newArrayList();
    List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
    for (FieldError fieldError : fieldErrorList) {
        ParameterInvalidItem parameterInvalidItem = new ParameterInvalidItem();
        parameterInvalidItem.setFieldName(fieldError.getField());
        parameterInvalidItem.setMessage(fieldError.getDefaultMessage());
        parameterInvalidItemList.add(parameterInvalidItem);
    }
    return parameterInvalidItemList;
}

18 View Source File : BaseController.java
License : Apache License 2.0
Project Creator : ash-ali

/**
 * 接口输入参数合法性校验
 *
 * @param result
 */
protected void validate(BindingResult result) {
    if (result.hasFieldErrors()) {
        List<FieldError> errorList = result.getFieldErrors();
        errorList.stream().forEach(item -> replacedert.isTrue(false, item.getDefaultMessage()));
    }
}

18 View Source File : ValidationUtil.java
License : GNU Lesser General Public License v2.1
Project Creator : abixen

public static List<FormErrorRepresentation> extractFormErrors(BindingResult result) {
    List<FormErrorRepresentation> formErrors = new ArrayList<>();
    for (FieldError fieldError : result.getFieldErrors()) {
        formErrors.add(new FormErrorRepresentation(fieldError));
    }
    return formErrors;
}

17 View Source File : ExceptionAdvice.java
License : Apache License 2.0
Project Creator : TraceNature

/*  数据校验处理 */
// @ExceptionHandler({BindException.clreplaced, ConstraintViolationException.clreplaced})
// public ResultMap validatorExceptionHandler(Exception e) {
// String msg = e instanceof BindException ? msgConvertor(((BindException) e).getBindingResult())
// : msgConvertor(((ConstraintViolationException) e).getConstraintViolations());
// 
// return ResultMap.builder().code(CodeConstant.VALITOR_ERROR_CODE)
// .msg(msg);
// 
// }
/**
 * 校验消息转换拼接
 *
 * @param bindingResult
 * @return
 */
public static String msgConvertor(BindingResult bindingResult) {
    List<FieldError> fieldErrors = bindingResult.getFieldErrors();
    StringBuilder sb = new StringBuilder();
    fieldErrors.forEach(fieldError -> sb.append(fieldError.getDefaultMessage()).append(","));
    return sb.deleteCharAt(sb.length() - 1).toString().toLowerCase();
}

17 View Source File : AdminController.java
License : GNU General Public License v3.0
Project Creator : mintster

private Boolean hreplacediteSettingsErrors(BindingResult result) {
    for (FieldError error : result.getFieldErrors()) {
        if (!error.getField().equals("integerProperty"))
            return true;
    }
    return false;
}

17 View Source File : IdentitiesEndpoint.java
License : MIT License
Project Creator : InnovateUKGitHub

private void throwExceptionOnInvalidPreplacedword(BindingResult bindingResult) throws InvalidPreplacedwordException {
    List<String> errors = bindingResult.getFieldErrors("preplacedword").stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
    throw new InvalidPreplacedwordException(errors);
}

17 View Source File : ControllerExceptionHandler.java
License : Mozilla Public License 2.0
Project Creator : hairless

@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public Result handlerNotValidException(MethodArgumentNotValidException exception) {
    BindingResult result = exception.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();
    return new Result(ResultCode.FAILURE, fieldErrors.get(0).getDefaultMessage());
}

17 View Source File : ValidateUtils.java
License : Apache License 2.0
Project Creator : EdurtIO

/**
 * 抽取验证错误的信息 TODO: 后期使用bean封装
 *
 * @param result 错误信息
 * @return 错误集合
 */
public static Map extractValidate(BindingResult result) {
    Map<String, Object> error = new HashMap<>();
    List<FieldError> allErrors = result.getFieldErrors();
    error.put("count", allErrors.size());
    List<Map<String, Object>> fields = new ArrayList<>();
    allErrors.forEach(v -> {
        Map<String, Object> field = new HashMap<>();
        field.put("field", v.getField());
        field.put("message", v.getDefaultMessage());
        fields.add(field);
    });
    error.put("error", fields);
    return error;
}

16 View Source File : BaseController.java
License : MIT License
Project Creator : roncoo

/**
 * 错误提示,不关闭当前对话框,自定义提示信息
 *
 * @param message
 *            提示信息
 * @return
 */
protected static String error(BindingResult bindingResult) {
    StringBuilder sb = new StringBuilder();
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        sb.append(fieldError.getDefaultMessage()).append("<br/>");
    }
    return error(sb.toString());
}

16 View Source File : GlobalException.java
License : MIT License
Project Creator : rexlin600

// -----------------------------------------------------------------------------------------------
// EXTRA METHOD
// -----------------------------------------------------------------------------------------------
/**
 * Build error message string
 *
 * @param bindingResult binding result
 * @return the string
 */
private String buildErrorMessage(BindingResult bindingResult) {
    StringBuilder sb = new StringBuilder("BindException. ");
    sb.append("Field error in object '").append(bindingResult.getObjectName()).append("'. ").append(bindingResult.getTarget()).append("]");
    bindingResult.getFieldErrors().forEach((error) -> {
        sb.append("\r\n on field '").append(error.getField()).append("': ");
        sb.append("rejected value [").append(error.getRejectedValue()).append("]. ");
        sb.append("default message [").append(error.getDefaultMessage()).append("]");
    });
    return sb.toString();
}

16 View Source File : ValidationErrorHandler.java
License : MIT License
Project Creator : manishsingh27

@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();
    return processFieldErrors(fieldErrors);
}

16 View Source File : ApplicationDetailsMarkAsCompleteValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub

@Test
public void valid_applicationDurationBeneathMinDurationShouldResultInError() {
    validApplication.setDurationInMonths(9L);
    DataBinder dataBinder = new DataBinder(validApplication);
    bindingResult = dataBinder.getBindingResult();
    validator.validate(validApplication, bindingResult);
    replacedertFalse(simpleFilter(bindingResult.getFieldErrors(), error -> error.getField().equals("durationInMonths") && error.getDefaultMessage().equals("validation.project.duration.input.invalid") && (Integer) error.getArguments()[0] == 10 && (Integer) error.getArguments()[1] == 20).isEmpty());
}

16 View Source File : ApplicationDetailsMarkAsCompleteValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub

@Test
public void valid_applicationDurationExceedsMaxDurationShouldResultInError() {
    validApplication.setDurationInMonths(21L);
    DataBinder dataBinder = new DataBinder(validApplication);
    bindingResult = dataBinder.getBindingResult();
    validator.validate(validApplication, bindingResult);
    replacedertFalse(simpleFilter(bindingResult.getFieldErrors(), error -> error.getField().equals("durationInMonths") && error.getDefaultMessage().equals("validation.project.duration.input.invalid") && (Integer) error.getArguments()[0] == 10 && (Integer) error.getArguments()[1] == 20).isEmpty());
}

15 View Source File : MessageController.java
License : Apache License 2.0
Project Creator : yuanmabiji

private Map<String, ObjectError> getFieldErrors(BindingResult result) {
    Map<String, ObjectError> map = new HashMap<>();
    for (FieldError error : result.getFieldErrors()) {
        map.put(error.getField(), error);
    }
    return map;
}

15 View Source File : RestExceptionAspect.java
License : MIT License
Project Creator : toesbieya

// 校验不通过
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    BindingResult bindingResult = e.getBindingResult();
    String error = bindingResult.getFieldErrors().get(0).getDefaultMessage();
    return R.fail(error);
}

15 View Source File : GlobalDefaultExceptionHandler.java
License : Apache License 2.0
Project Creator : suricate-io

/**
 * Method used to extract message from MethodArgumentNotValidException exception
 *
 * @param bindingResult Binding result
 * @return an error string
 */
private static String extractMessage(BindingResult bindingResult) {
    StringBuilder builder = new StringBuilder();
    for (FieldError error : bindingResult.getFieldErrors()) {
        if (builder.length() > 0) {
            builder.append(", ");
        }
        builder.append(error.getField()).append(' ').append(error.getDefaultMessage());
    }
    return builder.toString();
}

15 View Source File : GlobalExceptionHandler.java
License : Apache License 2.0
Project Creator : moxi624

/**
 * <p>
 * 自定义 REST 业务异常
 * <p>
 *
 * @param e 异常类型
 * @return
 */
@ExceptionHandler(value = Exception.clreplaced)
public R<Object> handleBadRequest(Exception e) {
    /*
         * 业务逻辑异常
         */
    if (e instanceof ApiException) {
        IErrorCode errorCode = ((ApiException) e).getErrorCode();
        if (null != errorCode) {
            log.debug("Rest request error, {}", errorCode.toString());
            return R.failed(errorCode);
        }
        log.debug("Rest request error, {}", e.getMessage());
        return R.failed(e.getMessage());
    }
    /*
         * 参数校验异常
         */
    if (e instanceof BindException) {
        BindingResult bindingResult = ((BindException) e).getBindingResult();
        if (null != bindingResult && bindingResult.hasErrors()) {
            List<Object> jsonList = new ArrayList<>();
            bindingResult.getFieldErrors().stream().forEach(fieldError -> {
                Map<String, Object> jsonObject = new HashMap<>(2);
                jsonObject.put("name", fieldError.getField());
                jsonObject.put("msg", fieldError.getDefaultMessage());
                jsonList.add(jsonObject);
            });
            return R.restResult(jsonList, ApiErrorCode.FAILED);
        }
    }
    /**
     * 系统内部异常,打印异常栈
     */
    log.error("Error: handleBadRequest StackTrace : {}", e);
    return R.failed(ApiErrorCode.FAILED);
}

15 View Source File : GlobalExceptionHandler.java
License : Apache License 2.0
Project Creator : lyh-man

/**
 * 处理 JSR303 校验的异常
 * @param e 异常
 * @return 处理结果
 */
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public Result handlerValidException(MethodArgumentNotValidException e) {
    logger.error(e.getMessage(), e);
    BindingResult result = e.getBindingResult();
    Map<String, String> map = new HashMap<>();
    // 获取校验结果,遍历获取捕获到的每个校验结果
    result.getFieldErrors().forEach(item -> {
        // 存储得到的校验结果
        map.put(item.getField(), item.getDefaultMessage());
    });
    return Result.error().message("数据校验不合法").data("items", map);
}

15 View Source File : AccountController.java
License : GNU Lesser General Public License v3.0
Project Creator : JustinSDK

private List<String> toList(BindingResult bindingResult) {
    List<String> errors = new ArrayList<>();
    if (bindingResult.hasErrors()) {
        bindingResult.getFieldErrors().forEach(err -> {
            errors.add(err.getDefaultMessage());
        });
    }
    return errors;
}

15 View Source File : RestExceptionTranslator.java
License : Apache License 2.0
Project Creator : joumenharzli

/**
 * Handle validation errors
 *
 * @return validation error with the fields errors and a bad request
 */
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.clreplaced)
@ResponseBody
public RestFieldsErrorsDto handleValidationExceptions(MethodArgumentNotValidException exception) {
    BindingResult result = exception.getBindingResult();
    String errorCode = RestErrorConstants.ERR_VALIDATION_ERROR;
    LOGGER.error(ERROR_MSG, errorCode, exception);
    RestFieldsErrorsDto restFieldsErrors = new RestFieldsErrorsDto(errorCode, getLocalizedMessageFromErrorCode(errorCode));
    List<FieldError> fieldErrors = result.getFieldErrors();
    fieldErrors.forEach(fieldError -> restFieldsErrors.addError(new RestFieldErrorDto(fieldError.getField(), fieldError.getCode(), getLocalizedMessageFromFieldError(fieldError))));
    return restFieldsErrors;
}

15 View Source File : ApplicationDetailsMarkAsCompleteValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub

@Test
public void valid_applicationDurationIsEqualToMaxAndMinDurationShouldNotResultInError() {
    validApplication.setDurationInMonths(10L);
    validApplication.setCompereplacedion(newCompereplacedion().withMinProjectDuration(10).withResubmission(false).withMaxProjectDuration(10).build());
    DataBinder dataBinder = new DataBinder(validApplication);
    bindingResult = dataBinder.getBindingResult();
    validator.validate(validApplication, bindingResult);
    replacedertTrue(simpleFilter(bindingResult.getFieldErrors(), error -> error.getField().equals("durationInMonths")).isEmpty());
}

15 View Source File : LogicExceptionHandler.java
License : Apache License 2.0
Project Creator : ch3n90

@ExceptionHandler({ MethodArgumentNotValidException.clreplaced })
public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
    BindingResult bindingResult = ex.getBindingResult();
    String msg = null;
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        msg = fieldError.getDefaultMessage();
    }
    return ResultBuilder.fail(msg);
}

15 View Source File : RestExceptionHandler.java
License : MIT License
Project Creator : AlicanAkkus

private Response<ErrorResponse> createFieldErrorResponse(BindingResult bindingResult, Locale locale) {
    List<String> requiredFieldErrorMessages = retrieveLocalizationMessage("common.client.requiredField", locale);
    String code = requiredFieldErrorMessages.get(0);
    String errorMessage = bindingResult.getFieldErrors().stream().map(FieldError::getField).map(error -> retrieveLocalizationMessage("common.client.requiredField", locale, error)).map(errorMessageList -> errorMessageList.get(1)).collect(Collectors.joining(" && "));
    log.debug("Exception occurred while request validation: {}", errorMessage);
    return respond(new ErrorResponse(code, errorMessage));
}

14 View Source File : CustomGlobalExceptionHandler.java
License : MIT License
Project Creator : wells2333

/**
 * 提取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));
    }
}

14 View Source File : ExceptionTranslator.java
License : Apache License 2.0
Project Creator : viz-centric

@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
@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;
}

14 View Source File : PublicController.java
License : GNU General Public License v3.0
Project Creator : silently9527

@PostMapping("/register2")
public ResponseEnreplacedy register2(@Valid RegisterVo2 registerVo, BindingResult result) {
    if (result.hasErrors()) {
        return ResponseEnreplacedy.failure(result.getFieldErrors().get(0).getDefaultMessage());
    }
    Base64.Encoder encoder = Base64.getEncoder();
    String orginalStr = "mobile=" + registerVo.getMobile() + "&inviteCode=" + registerVo.getInviteCode() + "&verifyCode=" + registerVo.getVerifyCode();
    String validSign = MD5Util.getMD5(encoder.encodeToString(orginalStr.getBytes()));
    if (!registerVo.getSign().equals(validSign)) {
        log.error("register2=>签名校验失败");
        return ResponseEnreplacedy.failure("签名校验失败");
    }
    userService.register2(registerVo);
    return ResponseEnreplacedy.success("注册成功");
}

14 View Source File : GlobalException.java
License : MIT License
Project Creator : rexlin600

/**
 * Handle response
 *
 * @param e e
 * @return the response
 */
@ExceptionHandler({ MethodArgumentNotValidException.clreplaced })
@ResponseBody
public Response<Void> handle(MethodArgumentNotValidException e) {
    BindingResult bindingResult = e.getBindingResult();
    String errorMessage = this.buildErrorMessage(bindingResult);
    log.warn(errorMessage);
    List<FieldError> fieldErrors = bindingResult.getFieldErrors();
    StringBuilder message = new StringBuilder();
    if (null != fieldErrors && fieldErrors.size() > 0) {
        for (int i = 0; i < fieldErrors.size(); i++) {
            message.append(Optional.ofNullable(fieldErrors.get(i)).map(m -> m.getDefaultMessage()).orElse("") + "  ");
        }
    }
    return ResponseGenerator.fail(StatusCode.PARAM_ERROR.getCode(), message.toString(), errorMessage);
}

14 View Source File : BaseController.java
License : Apache License 2.0
Project Creator : raysonfang

protected String validatedError(BindingResult result) {
    List<AjaxResult> errorList = new ArrayList<AjaxResult>();
    for (FieldError error : result.getFieldErrors()) {
        AjaxResult errorResult = new AjaxResult();
        errorResult.setCode(error.getField());
        errorResult.setMessage(error.getDefaultMessage());
        errorList.add(errorResult);
    }
    return JSONObject.toJSONString(errorList);
}

See More Examples