Search in sources :

Example 6 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project jhipster-sample-app-cassandra by jhipster.

the class ExceptionTranslator method handleMethodArgumentNotValid.

@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);
}
Also used : ControllerAdvice(org.springframework.web.bind.annotation.ControllerAdvice) BindingResult(org.springframework.validation.BindingResult) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ProblemHandling(org.zalando.problem.spring.web.advice.ProblemHandling) Collectors(java.util.stream.Collectors) DefaultProblem(org.zalando.problem.DefaultProblem) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) HeaderUtil(io.github.jhipster.sample.web.rest.util.HeaderUtil) Problem(org.zalando.problem.Problem) ProblemBuilder(org.zalando.problem.ProblemBuilder) Status(org.zalando.problem.Status) ConstraintViolationProblem(org.zalando.problem.spring.web.advice.validation.ConstraintViolationProblem) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseEntity(org.springframework.http.ResponseEntity) NoSuchElementException(java.util.NoSuchElementException) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) BindingResult(org.springframework.validation.BindingResult) DefaultProblem(org.zalando.problem.DefaultProblem) Problem(org.zalando.problem.Problem) ConstraintViolationProblem(org.zalando.problem.spring.web.advice.validation.ConstraintViolationProblem)

Example 7 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project flytecnologia-api by jullierme.

the class FlyValidatorUtil method validate.

public static void validate(Object entry, Class<?> targetClass, String methodName) throws MethodArgumentNotValidException {
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(entry, entry.getClass().getName());
    validator.validate(entry, errors);
    if (errors.hasErrors()) {
        Method method = null;
        for (Method methodAux : targetClass.getMethods()) {
            if (methodAux.getName().equals(methodName)) {
                method = methodAux;
                break;
            }
        }
        if (method != null) {
            MethodParameter methodParameter = new MethodParameter(method, 0);
            throw new MethodArgumentNotValidException(methodParameter, errors);
        } else {
            throw new InvalidDataException(errors.getAllErrors().toString(), errors);
        }
    }
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) InvalidDataException(com.flytecnologia.core.exception.InvalidDataException) Method(java.lang.reflect.Method) MethodParameter(org.springframework.core.MethodParameter) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException)

Example 8 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project Flare-event-calendar by PollubCafe.

the class GlobalExceptionHandler method handleMethodArgumentNotValid.

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    BindingResult bindingResult = ex.getBindingResult();
    List<ApiFieldError> apiFieldErrors = bindingResult.getFieldErrors().stream().map(fieldError -> new ApiFieldError(fieldError.getField(), fieldError.getDefaultMessage())).collect(toList());
    ApiErrorsView apiErrorsView = new ApiErrorsView(apiFieldErrors);
    return new ResponseEntity<>(apiErrorsView, HttpStatus.UNPROCESSABLE_ENTITY);
}
Also used : RegistrationException(pl.pollub.cs.pentagoncafe.flare.exception.registration.RegistrationException) SendingEmailException(pl.pollub.cs.pentagoncafe.flare.exception.sendingEmail.SendingEmailException) ObjectNotFoundException(pl.pollub.cs.pentagoncafe.flare.exception.ObjectNotFoundException) WebRequest(org.springframework.web.context.request.WebRequest) Autowired(org.springframework.beans.factory.annotation.Autowired) BindingResult(org.springframework.validation.BindingResult) ApiErrorsView(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiErrorsView) TooManyLoginAttempts(pl.pollub.cs.pentagoncafe.flare.exception.auth.TooManyLoginAttempts) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) EventCalendarApplication(pl.pollub.cs.pentagoncafe.flare.EventCalendarApplication) ControllerAdvice(org.springframework.web.bind.annotation.ControllerAdvice) Messages(pl.pollub.cs.pentagoncafe.flare.component.message.Messages) HttpHeaders(org.springframework.http.HttpHeaders) ResetPasswordException(pl.pollub.cs.pentagoncafe.flare.exception.ResetPasswordException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ApiFieldError(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiFieldError) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Logger(org.apache.logging.log4j.Logger) ResponseEntityExceptionHandler(org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler) ResponseEntity(org.springframework.http.ResponseEntity) LogManager(org.apache.logging.log4j.LogManager) BindingResult(org.springframework.validation.BindingResult) ResponseEntity(org.springframework.http.ResponseEntity) ApiErrorsView(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiErrorsView) ApiFieldError(pl.pollub.cs.pentagoncafe.flare.exception.handler.error.ApiFieldError)

Example 9 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project spring-framework by spring-projects.

the class DefaultHandlerExceptionResolverTests method handleMethodArgumentNotValid.

@Test
public void handleMethodArgumentNotValid() throws Exception {
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(new TestBean(), "testBean");
    errors.rejectValue("name", "invalid");
    MethodParameter parameter = new MethodParameter(this.getClass().getMethod("handle", String.class), 0);
    MethodArgumentNotValidException ex = new MethodArgumentNotValidException(parameter, errors);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertThat(mav).as("No ModelAndView returned").isNotNull();
    assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
    assertThat(response.getStatus()).as("Invalid status code").isEqualTo(400);
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) TestBean(org.springframework.beans.testfixture.beans.TestBean) ModelAndView(org.springframework.web.servlet.ModelAndView) MethodParameter(org.springframework.core.MethodParameter) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) Test(org.junit.jupiter.api.Test)

Example 10 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project spring-framework by spring-projects.

the class RequestResponseBodyMethodProcessor method resolveArgument.

/**
 * 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, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
    parameter = parameter.nestedIfOptional();
    Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
    String name = Conventions.getVariableNameForParameter(parameter);
    if (binderFactory != null) {
        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());
            }
        }
        if (mavContainer != null) {
            mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
        }
    }
    return adaptArgumentIfNecessary(arg, parameter);
}
Also used : WebDataBinder(org.springframework.web.bind.WebDataBinder) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException)

Aggregations

MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)27 List (java.util.List)18 BindingResult (org.springframework.validation.BindingResult)17 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)17 ResponseEntity (org.springframework.http.ResponseEntity)16 ControllerAdvice (org.springframework.web.bind.annotation.ControllerAdvice)16 Collectors (java.util.stream.Collectors)15 Nonnull (javax.annotation.Nonnull)13 Nullable (javax.annotation.Nullable)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)13 DefaultProblem (org.zalando.problem.DefaultProblem)13 Problem (org.zalando.problem.Problem)13 ProblemBuilder (org.zalando.problem.ProblemBuilder)13 Status (org.zalando.problem.Status)13 ProblemHandling (org.zalando.problem.spring.web.advice.ProblemHandling)13 ConstraintViolationProblem (org.zalando.problem.spring.web.advice.validation.ConstraintViolationProblem)13 ConcurrencyFailureException (org.springframework.dao.ConcurrencyFailureException)12 HeaderUtil (io.github.jhipster.sample.web.rest.util.HeaderUtil)7 NoSuchElementException (java.util.NoSuchElementException)7