Java Code Examples for org.springframework.web.bind.MethodArgumentNotValidException#getBindingResult()

The following examples show how to use org.springframework.web.bind.MethodArgumentNotValidException#getBindingResult() . 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: SystemExceptionHandler.java    From codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * JSR303参数校验错误
 * @param ex BindException
 */
@ExceptionHandler({BindException.class,MethodArgumentNotValidException.class})
public JsonData<Void> bindException(MethodArgumentNotValidException ex) {
	LogBack.error(ex.getMessage(), ex);
	BindingResult bindingResult = ex.getBindingResult();
	if (bindingResult.hasErrors()) {
		List<FieldError> errors = bindingResult.getFieldErrors();
		List<ValidFieldError> validList = new ArrayList<>();
		if (!(CollectionUtils.isEmpty(errors))) {
			for (FieldError fe : errors) {
				validList.add(new ValidFieldError(fe));
			}
		}
		LogBack.error("参数校验错误:" + validList.toString(), ex);
		return JsonData.failed(StatusEnum.PARAM_INVALID, validList.toString());
	}
	return JsonData.failed(StatusEnum.PARAM_INVALID);
}
 
Example 2
Source File: ExceptionTranslator.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 3
Source File: RestExceptionTranslator.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Handle validation errors
 *
 * @return validation error with the fields errors and a bad request
 */
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@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;

}
 
Example 4
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 5
Source File: ExceptionTranslator.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 6
Source File: SystemExceptionHandler.java    From codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * JSR303参数校验错误
 * @param ex BindException
 */
@ExceptionHandler({BindException.class,MethodArgumentNotValidException.class})
public JsonData<Void> bindException(MethodArgumentNotValidException ex) {
	LogBack.error(ex.getMessage(), ex);
	BindingResult bindingResult = ex.getBindingResult();
	if (bindingResult.hasErrors()) {
		List<FieldError> errors = bindingResult.getFieldErrors();
		List<ValidFieldError> validList = new ArrayList<>();
		if (!(CollectionUtils.isEmpty(errors))) {
			for (FieldError fe : errors) {
				validList.add(new ValidFieldError(fe));
			}
		}
		LogBack.error("参数校验错误:" + validList.toString(), ex);
		return JsonData.failed(StatusEnum.PARAM_INVALID, validList.toString());
	}
	return JsonData.failed(StatusEnum.PARAM_INVALID);
}
 
Example 7
Source File: ExceptionTranslator.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 8
Source File: RestExceptionTranslator.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Handle validation errors
 *
 * @return validation error with the fields errors and a bad request
 */
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@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;

}
 
Example 9
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 10
Source File: ExceptionTranslator.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 11
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 12
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 13
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 14
Source File: ExceptionTranslator.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * body参数校验失败
 *
 * @param ex
 * @return
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResponseEntity<ReplyVO> processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    return processBindingResult(result);
}
 
Example 15
Source File: GlobalDefaultExceptionHandler.java    From watchdog-framework with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
    BindingResult result = e.getBindingResult();
    String s = "参数验证失败";
    if(result.hasErrors()){
        List<ObjectError> errors = result.getAllErrors();
        s = errors.get(0).getDefaultMessage();
    }
    return ResponseResult.builder().status(ResponseCode.FAIL.code).msg(s).build();
}
 
Example 16
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 17
Source File: GlobalExceptionHandler.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
/**
 * 非法参数验证异常
 *
 * @param ex
 * @return
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.OK)
public ApiResult<List<String>> handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
    printRequestDetail();
    BindingResult bindingResult = ex.getBindingResult();
    List<String> list = new ArrayList<>();
    List<FieldError> fieldErrors = bindingResult.getFieldErrors();
    for (FieldError fieldError : fieldErrors) {
        list.add(fieldError.getDefaultMessage());
    }
    Collections.sort(list);
    log.error(getApiCodeString(ApiCode.PARAMETER_EXCEPTION) + ":" + JSON.toJSONString(list));
    return ApiResult.fail(ApiCode.PARAMETER_EXCEPTION, list);
}
 
Example 18
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 19
Source File: ControllerExceptionHandleAdvice.java    From seppb with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public GenericResponse valid(MethodArgumentNotValidException e) {
    BindingResult bindingResult = e.getBindingResult();
    List<ObjectError> allErrors = bindingResult.getAllErrors();
    List<String> errorMessages = allErrors.stream().map(ObjectError::getDefaultMessage).collect(toList());
    String message = StringUtils.join(errorMessages, ";");
    return GenericResponse.CLIENT_ERROR.setMessage(message);
}
 
Example 20
Source File: GlobalExceptionTranslator.java    From staffjoy with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseResponse handleError(MethodArgumentNotValidException e) {
    logger.warn("Method Argument Not Valid", e);
    BindingResult result = e.getBindingResult();
    FieldError error = result.getFieldError();
    String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
    return BaseResponse
            .builder()
            .code(ResultCode.PARAM_VALID_ERROR)
            .message(message)
            .build();
}