本文整理汇总了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;
}
示例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);
}
示例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);
}
示例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));
}
示例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));
}
}
示例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);
}
示例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();
}
示例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);
}
示例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;
}
示例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;
}
};
}
示例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;
}
}
}
示例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);
}