Search in sources :

Example 21 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project spring-cloud-open-service-broker by spring-cloud.

the class BaseControllerTest method methodArgumentNotValidExceptionGivesExpectedStatus.

@Test
public void methodArgumentNotValidExceptionGivesExpectedStatus() throws NoSuchMethodException {
    BindingResult bindingResult = new MapBindingResult(new HashMap<>(), "objectName");
    bindingResult.addError(new FieldError("objectName", "field1", "message"));
    bindingResult.addError(new FieldError("objectName", "field2", "message"));
    Method method = this.getClass().getMethod("setUp", (Class<?>[]) null);
    MethodParameter parameter = new MethodParameter(method, -1);
    MethodArgumentNotValidException exception = new MethodArgumentNotValidException(parameter, bindingResult);
    ResponseEntity<ErrorMessage> responseEntity = controller.handleException(exception);
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.UNPROCESSABLE_ENTITY);
    assertThat(responseEntity.getBody().getError()).isNull();
    assertThat(responseEntity.getBody().getMessage()).contains("field1");
    assertThat(responseEntity.getBody().getMessage()).contains("field2");
}
Also used : BindingResult(org.springframework.validation.BindingResult) MapBindingResult(org.springframework.validation.MapBindingResult) MapBindingResult(org.springframework.validation.MapBindingResult) FieldError(org.springframework.validation.FieldError) Method(java.lang.reflect.Method) MethodParameter(org.springframework.core.MethodParameter) ErrorMessage(org.springframework.cloud.servicebroker.model.error.ErrorMessage) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) Test(org.junit.Test)

Example 22 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project jim-framework by jiangmin168168.

the class BaseController method exception.

@ExceptionHandler
public ValueResult exception(HttpServletRequest request, Exception ex) {
    ValueResult result = new ValueResult();
    if (ex instanceof ConstraintViolationException) {
        ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex;
        Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
        String errorMsg = this.getConstraintViolationsMsg(constraintViolations);
        result.setError(new ErrorInfo(ErrorDef.InvalidParameters.getCode(), errorMsg));
        result.setResult(false);
    } else if (ex instanceof MethodArgumentNotValidException) {
        MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
        List<ObjectError> allErrors = methodArgumentNotValidException.getBindingResult().getAllErrors();
        String errorMsg = this.getAllParametersInValidMsg(allErrors);
        result.setError(new ErrorInfo(ErrorDef.InvalidParameters.getCode(), errorMsg));
    } else {
        logger.error("system error", ex);
        result.setError(new ErrorInfo(ErrorDef.ServerError.getCode(), ex.getMessage()));
        result.setResult(false);
    }
    return result;
}
Also used : ValueResult(com.jim.framework.web.common.ValueResult) ConstraintViolation(javax.validation.ConstraintViolation) ErrorInfo(com.jim.framework.web.common.ErrorInfo) ConstraintViolationException(javax.validation.ConstraintViolationException) List(java.util.List) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler)

Example 23 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project spring-boot-jpa by ssherwood.

the class BootJpaApplication method errorAttributes.

/**
 * 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;
        }
    };
}
Also used : RequestAttributes(org.springframework.web.context.request.RequestAttributes) DefaultErrorAttributes(org.springframework.boot.autoconfigure.web.DefaultErrorAttributes) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) Bean(org.springframework.context.annotation.Bean)

Example 24 with MethodArgumentNotValidException

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

the class RequestPartMethodArgumentResolver method resolveArgument.

@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {
    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    Assert.state(servletRequest != null, "No HttpServletRequest");
    RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
    boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());
    String name = getPartName(parameter, requestPart);
    parameter = parameter.nestedIfOptional();
    Object arg = null;
    Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
    if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
        arg = mpArg;
    } else {
        try {
            HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
            arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
            if (binderFactory != null) {
                WebDataBinder binder = binderFactory.createBinder(request, 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());
                }
            }
        } catch (MissingServletRequestPartException | MultipartException ex) {
            if (isRequired) {
                throw ex;
            }
        }
    }
    if (arg == null && isRequired) {
        if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
            throw new MultipartException("Current request is not a multipart request");
        } else {
            throw new MissingServletRequestPartException(name);
        }
    }
    return adaptArgumentIfNecessary(arg, parameter);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpInputMessage(org.springframework.http.HttpInputMessage) WebDataBinder(org.springframework.web.bind.WebDataBinder) MissingServletRequestPartException(org.springframework.web.multipart.support.MissingServletRequestPartException) RequestPart(org.springframework.web.bind.annotation.RequestPart) MultipartException(org.springframework.web.multipart.MultipartException) RequestPartServletServerHttpRequest(org.springframework.web.multipart.support.RequestPartServletServerHttpRequest) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) Nullable(org.springframework.lang.Nullable)

Example 25 with MethodArgumentNotValidException

use of org.springframework.web.bind.MethodArgumentNotValidException in project chassis by Kixeye.

the class RawWebSocketMessage method deserialize.

/**
 * Deserializes the given message.
 *
 * @param action
 * @return
 * @throws Exception
 */
public T deserialize(WebSocketAction action) throws Exception {
    // first deserialize
    T message = null;
    if (messageClass != null) {
        message = serDe.deserialize(new ByteBufferBackedInputStream(rawData), messageClass);
    }
    // then validate
    if (message != null && action.shouldValidatePayload()) {
        SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter(messageValidator);
        BeanPropertyBindingResult result = new BeanPropertyBindingResult(message, messageClass.getName());
        validatorAdapter.validate(message, result);
        if (result.hasErrors()) {
            throw new MethodArgumentNotValidException(new MethodParameter(action.getMethod(), action.getPayloadParameterIndex()), result);
        }
    }
    return message;
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) SpringValidatorAdapter(org.springframework.validation.beanvalidation.SpringValidatorAdapter) MethodParameter(org.springframework.core.MethodParameter) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ByteBufferBackedInputStream(com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream)

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