Java 类org.springframework.web.bind.MethodArgumentNotValidException 实例源码

项目:meparty    文件:TestValidationHandler.java   
/**
 * Rest handler for validation errors.
 * @param ex handled exception
 * @return rest result
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) {

  BindingResult bindingResult = ex.getBindingResult();
  List<FieldError> fieldErrors = bindingResult.getFieldErrors();
  List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream()
      .map(FieldErrorDto::new)
      .collect(Collectors.toList());

  ValidationResultDto validationResultDto = new ValidationResultDto();
  validationResultDto.setFieldErrors(fieldErrorDtos);

  return ResponseEntity.badRequest().body(validationResultDto);
}
项目:meparty    文件:ValidationErrorHandler.java   
/**
 * Rest handler for validation errors.
 * @param ex handled exception
 * @return rest result
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) {

  BindingResult bindingResult = ex.getBindingResult();
  List<FieldError> fieldErrors = bindingResult.getFieldErrors();
  List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream()
      .map(FieldErrorDto::new)
      .collect(Collectors.toList());

  ValidationResultDto validationResultDto = new ValidationResultDto();
  validationResultDto.setFieldErrors(fieldErrorDtos);

  LOGGER.error("VALIDATION ERROR: " + ex.getMessage());

  return ResponseEntity.badRequest().body(validationResultDto);
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:jhipster-microservices-example    文件:ExceptionTranslatorTest.java   
@Test
public void processValidationErrorTest() throws Exception {
    UserJWTController control = new UserJWTController(null, null);
    MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control)
        .setControllerAdvice(new ExceptionTranslator())
        .build();
    MvcResult res = jwtMock.perform(post("/api/authenticate")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL)
        .content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" +
            "\",\"password\":\"fakePassword\",\"rememberMe\":false}"))
        .andExpect(status().isBadRequest())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class));
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:document-management-store-app    文件:StoredDocumentController.java   
@PostMapping(value = "", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiOperation("Creates a list of Stored Documents by uploading a list of binary/text files.")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Success", response = StoredDocumentHalResourceCollection.class)
})
public ResponseEntity<Object> createFrom(
        @Valid UploadDocumentsCommand uploadDocumentsCommand,
        BindingResult result) throws MethodArgumentNotValidException {

    if (result.hasErrors()) {
        throw new MethodArgumentNotValidException(uploadDocumentsCommandMethodParameter, result);
    } else {
        List<StoredDocument> storedDocuments =
                auditedStoredDocumentOperationsService.createStoredDocuments(uploadDocumentsCommand);
        return ResponseEntity
                .ok()
                .contentType(V1MediaType.V1_HAL_DOCUMENT_COLLECTION_MEDIA_TYPE)
                .body(new StoredDocumentHalResourceCollection(storedDocuments));
    }
}
项目:TorgCRM-Server    文件:ExceptionTranslator.java   
@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);
}
项目:codemotion-2017-taller-de-jhipster    文件:ExceptionTranslator.java   
@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);
}
项目:qualitoast    文件:ExceptionTranslator.java   
@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);
}
项目:OpenLRW    文件:XAPIExceptionHandlerAdvice.java   
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) {
    final List<String> errorMessages = new ArrayList<String>();
    for (ObjectError oe : e.getBindingResult().getAllErrors()) {
        if (oe instanceof FieldError) {
            final FieldError fe = (FieldError)oe;
            final String msg = String.format(
                    "Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue());
            errorMessages.add(msg);
        } else {
            errorMessages.add(oe.toString());
        }
    }
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages);
    this.logException(e);
    this.logError(result);
    return result;
}
项目:project-template    文件:ValidationErrorHandlers.java   
@Loggable
@ResponseStatus(code = HttpStatus.CONFLICT)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ErrorDto handleValidationError(MethodArgumentNotValidException ex) {
    Set<ValidationErrorDto> errors = ex.getBindingResult().getFieldErrors().stream()
            .map(err -> ValidationErrorDto.builder()
                    .errorCode(err.getCode())
                    .fieldName(err.getField())
                    .rejectedValue(err.getRejectedValue())
                    .params(Stream.of(err.getArguments())
                            .skip(1)
                            .map(Object::toString)
                            .collect(Collectors.toList()))
                    .message(err.getDefaultMessage())
                    .build())
            .collect(Collectors.toSet());

    return ErrorDto.builder()
            .errorCode(ErrorCodes.DATA_VALIDATION)
            .errors(Collections.unmodifiableSet(errors))
            .message(ex.getLocalizedMessage())
            .build();
}
项目:spring-security-rest    文件:UserController.java   
@ResponseBody
@RequestMapping(method = RequestMethod.PUT, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<User> update(@Validated @RequestBody User user, BindingResult bindingResult, Authentication authentication) throws ServiceException, MethodArgumentNotValidException, NoSuchMethodException, SecurityException {

    if(user != null && !user.getUsername().equals(authentication.getName()) && !authentication.getAuthorities().contains(new Role("ROLE_ADMIN"))){
        throw new AccessDeniedException("Access is denied");
    }

    if(user != null && StringUtils.isEmpty(user.getId())){
        bindingResult.rejectValue("id", "id.empty");
    }

    if(bindingResult.hasErrors()){
        throw new MethodArgumentNotValidException(new MethodParameter(User.class.getConstructor(), 0), bindingResult);
    }

    user = userService.update(user);
    return new ResponseEntity<User>(user, HttpStatus.OK);
}
项目:spring4-understanding    文件:RequestResponseBodyMethodProcessor.java   
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    Object arg = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType());
    String name = Conventions.getVariableNameForParameter(parameter);

    WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
    if (arg != null) {
        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
            throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
        }
    }
    mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

    return arg;
}
项目:backstopper    文件:ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java   
@Override
public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) {

    SortedApiErrorSet handledErrors = null;

    if (ex instanceof MethodArgumentNotValidException) {
        handledErrors = convertSpringErrorsToApiErrors(
            ((MethodArgumentNotValidException) ex).getBindingResult().getAllErrors()
        );
    }

    if (ex instanceof BindException) {
        handledErrors = convertSpringErrorsToApiErrors(((BindException) ex).getAllErrors());
    }

    if (handledErrors != null) {
        return ApiExceptionHandlerListenerResult.handleResponse(handledErrors);
    }

    return ApiExceptionHandlerListenerResult.ignoreResponse();
}
项目:backstopper    文件:ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java   
@Test
public void shouldCreateValidationErrorsForMethodArgumentNotValidException() {
    MethodParameter methodParam = mock(MethodParameter.class);
    BindingResult bindingResult = mock(BindingResult.class);

    List<ObjectError> errorsList = Collections.<ObjectError>singletonList(
        new FieldError("someObj", "someField", testProjectApiErrors.getMissingExpectedContentApiError().getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    MethodArgumentNotValidException ex = new MethodArgumentNotValidException(methodParam, bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Collections.singletonList(
        new ApiErrorWithMetadata(testProjectApiErrors.getMissingExpectedContentApiError(),
                                 Pair.of("field", (Object)"someField"))
    ));
    verify(bindingResult).getAllErrors();
}
项目:spring-boot-jpa    文件:BootJpaApplication.java   
/**
 * Customized ErrorAttribute bean.
 * We really need to find a cleaner way of handling these error messages.
 *
 * @return customized ErrorAttributes
 */
@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {

        @Override
        public Map<String, Object> getErrorAttributes(
                final RequestAttributes requestAttributes,
                final boolean includeStackTrace) {
            Map<String, Object> attributes = super
                    .getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);

            if (error instanceof MethodArgumentNotValidException) {
                MethodArgumentNotValidException ex =
                        ((MethodArgumentNotValidException) error);
                attributes.put("errors", ex.getMessage());
            }

            return attributes;
        }
    };
}
项目:nbone    文件:JsonRequestBodyMethodProcessor.java   
private void validate(WebDataBinder binder, MethodParameter parameter) throws Exception, MethodArgumentNotValidException {

        Annotation[] annotations = parameter.getParameterAnnotations();
        for (Annotation annot : annotations) {
            if (annot.annotationType().getSimpleName().startsWith("Valid")) {
                Object hints = AnnotationUtils.getValue(annot);
                binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
                BindingResult bindingResult = binder.getBindingResult();
                if (bindingResult.hasErrors()) {
                    if (isBindExceptionRequired(binder, parameter)) {
                        throw new MethodArgumentNotValidException(parameter, bindingResult);
                    }
                }
                break;
            }
        }
    }
项目:jhipster-registry    文件:ExceptionTranslatorTest.java   
@Test
public void processValidationErrorTest() throws Exception {
    UserJWTController control = new UserJWTController(null, null);
    MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control)
        .setControllerAdvice(new ExceptionTranslator())
        .build();
    MvcResult res = jwtMock.perform(post("/api/authenticate")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL)
        .content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" +
            "\",\"password\":\"fakePassword\",\"rememberMe\":false}"))
        .andExpect(status().isBadRequest())
        .andReturn();

    assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class));
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:MTC_Labrat    文件:ExceptionTranslator.java   
@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;
}
项目:REST-Web-Services    文件:ErrorFieldsExceptionHandler.java   
/**
 * @param ex {@link MethodArgumentNotValidException}
 * @return Returns an object with a list of error fields
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ValidationErrorDTO processValidationError(final MethodArgumentNotValidException ex) {
    final BindingResult result = ex.getBindingResult();
    final List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}
项目:buenojo    文件:ExceptionTranslator.java   
@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);
}
项目:xm-commons    文件:ExceptionTranslator.java   
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    FieldErrorVM dto = new FieldErrorVM(ErrorConstants.ERR_VALIDATION, translate(ErrorConstants.ERR_VALIDATION));
    for (FieldError fieldError : result.getFieldErrors()) {
        dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode());
    }
    for (ObjectError globalError : result.getGlobalErrors()) {
        dto.add(globalError.getObjectName(), globalError.getObjectName(), globalError.getCode());
    }
    return dto;
}
项目:document-management-store-app    文件:ExceptionStatusCodeAndMessageResolver.java   
@PostConstruct
public void init() {
    exceptionToStatusCodeMap.put(FileUploadBase.FileSizeLimitExceededException.class, 413);
    exceptionToStatusCodeMap.put(FileUploadBase.SizeLimitExceededException.class, 413);
    exceptionToStatusCodeMap.put(MethodArgumentTypeMismatchException.class, 404);
    exceptionToStatusCodeMap.put(MethodArgumentNotValidException.class, 422);

    exceptionToMessageMap.put(MethodArgumentNotValidException.class, "Request validation failed");
}
项目:Armory    文件:ExceptionTranslator.java   
@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);
}
项目:Armory    文件:ExceptionTranslator.java   
@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;
}
项目:sweiproject-tg2b-1    文件:ExceptionController.java   
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception,
                                                              HttpHeaders headers,
                                                              HttpStatus status,
                                                              WebRequest request) {
    logger.error(CLIENT_ERROR, exception);
    final BindingResult bindingResult = exception.getBindingResult();
    final GenericResponse bodyOfResponse = new GenericResponse(bindingResult.getAllErrors(),
            "Invalid" + bindingResult.getObjectName());
    return handleExceptionInternal(exception, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
项目:patient-portal    文件:ExceptionTranslator.java   
@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;
}
项目:sentry    文件:ExceptionTranslator.java   
@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);
}
项目:sns-todo    文件:WebGlobalHandler.java   
@ExceptionHandler(MethodArgumentNotValidException.class)
public ModelAndView handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    log.error("MethodArgumentNotValidException:{},url:{}", e.getMessage(), RequestHolder.getLastAccessUri());
    StringBuilder builder = new StringBuilder();
    for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
        builder.append(fieldError.getField())
                .append(":")
                .append(fieldError.getDefaultMessage())
                .append(System.lineSeparator());
    }
    ModelAndView modelAndView = new ModelAndView("error");
    modelAndView.addObject("message", builder.toString());
    return modelAndView;
}
项目:speakTogether    文件:ExceptionTranslator.java   
@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;
}
项目:Code4Health-Platform    文件:ExceptionTranslator.java   
@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);
}
项目:remember-me-back    文件:ValidationController.java   
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public List<ErrorMessage> processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    List<FieldError> error = result.getFieldErrors();
    return processFieldError(error);
}
项目:metamodel-membrane    文件:RestErrorHandler.java   
/**
 * Method binding issues (raised by Spring framework) - mapped to BAD_REQUEST.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestErrorResponse processValidationError(MethodArgumentNotValidException ex) {
    final BindingResult result = ex.getBindingResult();

    final Map<String, Object> globalErrorsMap = new LinkedHashMap<>();
    final List<ObjectError> globalErrors = result.getGlobalErrors();
    for (ObjectError objectError : globalErrors) {
        globalErrorsMap.put(objectError.getObjectName(), objectError.getDefaultMessage());
    }

    final List<FieldError> fieldErrors = result.getFieldErrors();
    final Map<String, Object> fieldErrorsMap = new LinkedHashMap<>();
    for (FieldError fieldError : fieldErrors) {
        fieldErrorsMap.put(fieldError.getObjectName() + '.' + fieldError.getField(),
                fieldError.getDefaultMessage());
    }

    final Map<String, Object> additionalDetails = new LinkedHashMap<>();
    if (!globalErrorsMap.isEmpty()) {
        additionalDetails.put("global-errors", globalErrorsMap);
    }
    if (!fieldErrorsMap.isEmpty()) {
        additionalDetails.put("field-errors", fieldErrorsMap);
    }
    final RestErrorResponse errorResponse =
            new RestErrorResponse(HttpStatus.BAD_REQUEST.value(), "Failed to validate request");
    if (!additionalDetails.isEmpty()) {
        errorResponse.setAdditionalDetails(additionalDetails);
    }
    return errorResponse;
}
项目:spring-web-services    文件:CustomizedResponseEntityExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "Validation Failed",
            ex.getBindingResult().toString());
    return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
项目:spring-io    文件:ExceptionTranslator.java   
@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;
}
项目:spring-io    文件:ExceptionTranslator.java   
@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;
}
项目:spring-io    文件:ExceptionTranslator.java   
@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;
}
项目:spring-io    文件:ExceptionTranslator.java   
@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;
}
项目:stuffEngine    文件:GlobalExceptionHandlerController.java   
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> validationProblem(MethodArgumentNotValidException e){
    logger.error(e.getMessage());
    List<ObjectError> errors= e.getBindingResult().getAllErrors();
    List<CommonError> myErrors = new ArrayList<>();
    for (ObjectError err: errors
            ) {
        myErrors.add(new CommonError(err.getDefaultMessage()));
    }
    return new ResponseEntity<>(myErrors, HttpStatus.BAD_REQUEST);
}