/** * 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); }
/** * 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); }
@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; }
@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)); }
@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)); } }
@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); }
@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; }
@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(); }
@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); }
/** * 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; }
@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(); }
@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(); }
/** * 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; } }; }
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; } } }
/** * @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); }
@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); }
@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; }
@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"); }
@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); }
@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); }
@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; }
@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); }
/** * 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; }
@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); }
@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); }