当前位置: 首页>>代码示例>>Java>>正文


Java MethodArgumentNotValidException类代码示例

本文整理汇总了Java中org.springframework.web.bind.MethodArgumentNotValidException的典型用法代码示例。如果您正苦于以下问题:Java MethodArgumentNotValidException类的具体用法?Java MethodArgumentNotValidException怎么用?Java MethodArgumentNotValidException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MethodArgumentNotValidException类属于org.springframework.web.bind包,在下文中一共展示了MethodArgumentNotValidException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: processValidationError

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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;
}
 
开发者ID:oktadeveloper,项目名称:jhipster-microservices-example,代码行数:13,代码来源:ExceptionTranslator.java

示例2: processHandler

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:mental-party,项目名称:meparty,代码行数:21,代码来源:TestValidationHandler.java

示例3: handleMethodArgumentNotValidException

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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;
}
 
开发者ID:Apereo-Learning-Analytics-Initiative,项目名称:OpenLRW,代码行数:21,代码来源:XAPIExceptionHandlerAdvice.java

示例4: processHandler

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:mental-party,项目名称:meparty,代码行数:23,代码来源:ValidationErrorHandler.java

示例5: processValidationErrorTest

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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));
}
 
开发者ID:oktadeveloper,项目名称:jhipster-microservices-example,代码行数:17,代码来源:ExceptionTranslatorTest.java

示例6: createFrom

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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));
    }
}
 
开发者ID:hmcts,项目名称:document-management-store-app,代码行数:21,代码来源:StoredDocumentController.java

示例7: handleMethodArgumentNotValid

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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);
}
 
开发者ID:torgcrm,项目名称:TorgCRM-Server,代码行数:17,代码来源:ExceptionTranslator.java

示例8: handleValidationError

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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();
}
 
开发者ID:rozidan,项目名称:project-template,代码行数:24,代码来源:ValidationErrorHandlers.java

示例9: update

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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);
}
 
开发者ID:francisco-gcd,项目名称:spring-security-rest,代码行数:20,代码来源:UserController.java

示例10: resolveArgument

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:25,代码来源:RequestResponseBodyMethodProcessor.java

示例11: shouldHandleException

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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();
}
 
开发者ID:Nike-Inc,项目名称:backstopper,代码行数:22,代码来源:ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java

示例12: shouldCreateValidationErrorsForMethodArgumentNotValidException

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
@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();
}
 
开发者ID:Nike-Inc,项目名称:backstopper,代码行数:20,代码来源:ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java

示例13: errorAttributes

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
/**
 * 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;
		}
	};
}
 
开发者ID:ssherwood,项目名称:spring-boot-jpa,代码行数:29,代码来源:BootJpaApplication.java

示例14: validate

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
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;
			}
		}
	}
 
开发者ID:thinking-github,项目名称:nbone,代码行数:18,代码来源:JsonRequestBodyMethodProcessor.java

示例15: processValidationError

import org.springframework.web.bind.MethodArgumentNotValidException; //导入依赖的package包/类
/**
 * @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);
}
 
开发者ID:JonkiPro,项目名称:REST-Web-Services,代码行数:13,代码来源:ErrorFieldsExceptionHandler.java


注:本文中的org.springframework.web.bind.MethodArgumentNotValidException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。