當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。