Example usage for org.springframework.web.bind MethodArgumentNotValidException getBindingResult

List of usage examples for org.springframework.web.bind MethodArgumentNotValidException getBindingResult

Introduction

In this page you can find the example usage for org.springframework.web.bind MethodArgumentNotValidException getBindingResult.

Prototype

public BindingResult getBindingResult() 

Source Link

Document

Return the results of the failed validation.

Usage

From source file:it.smartcommunitylab.aac.controller.AdminController.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)/*from w ww  .  java  2  s  .co m*/
@ResponseBody
public Response processValidationError(MethodArgumentNotValidException ex) {
    BindingResult br = ex.getBindingResult();
    List<FieldError> fieldErrors = br.getFieldErrors();
    StringBuilder builder = new StringBuilder();

    fieldErrors.forEach(fe -> builder.append(fe.getDefaultMessage()).append("\n"));

    return Response.error(builder.toString());
}

From source file:gt.org.ms.api.global.GlobalExceptionHandler.java

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {

    List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
    List<ValidationError> errors = new ArrayList<ValidationError>();

    for (FieldError fieldError : fieldErrors) {
        errors.add(// w w  w .ja va  2  s.co m
                new ValidationError(fieldError.getField().replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase(),
                        translateValidationMessage(fieldError.getDefaultMessage())));
    }

    ValidationException ve = new ValidationException(errors);
    LOG.info("ValidationException", ve);
    return handleException(ve);
}

From source file:cz.jirutka.spring.exhandler.handlers.MethodArgumentNotValidExceptionHandler.java

@Override
public ValidationErrorMessage createBody(MethodArgumentNotValidException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    BindingResult result = ex.getBindingResult();

    for (ObjectError err : result.getGlobalErrors()) {
        msg.addError(err.getDefaultMessage());
    }//from www .ja v  a  2  s  .c o  m
    for (FieldError err : result.getFieldErrors()) {
        msg.addError(err.getField(), err.getRejectedValue(), err.getDefaultMessage());
    }
    return msg;
}

From source file:be.bittich.quote.controller.impl.DefaultExceptionHandler.java

private Map<String, Map<String, Object>> convertConstraintViolation(MethodArgumentNotValidException ex) {
    Map<String, Map<String, Object>> result = newHashMap();
    ex.getBindingResult().getAllErrors().stream().forEach((error) -> {
        Map<String, Object> violationMap = newHashMap();
        violationMap.put("target", ex.getBindingResult().getTarget());
        violationMap.put("type", ex.getBindingResult().getTarget().getClass());
        violationMap.put("message", error.getDefaultMessage());
        result.put(error.getObjectName(), violationMap);
    });/*w  w w  .j a va 2 s .  c  om*/
    return result;
}

From source file:com.todo.backend.web.rest.exception.ExceptionResolver.java

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public @ResponseBody ErrorResponse validationException(HttpServletRequest request,
        MethodArgumentNotValidException exception) {
    if (log.isErrorEnabled()) {
        log.error(exception.getMessage(), exception);
    }/* w w  w.j a  v  a 2s .c o m*/
    final List<String> errorCodes = exception.getBindingResult().getFieldErrors().stream()
            .map(e -> String.format("%s.%s.%s", e.getObjectName(), e.getField(), e.getCode()))
            .collect(Collectors.toList());
    return new ErrorResponse(exception.getMessage(), errorCodes);
}

From source file:org.exoplatform.acceptance.rest.JsonErrorHandler.java

/**
 * Catch MethodArgumentNotValidException when a Bean Validation error occurs.
 *
 * @param ex The exception trapped/*w ww  .  java 2  s .co m*/
 * @return A standardized {@link org.exoplatform.acceptance.rest.JsonErrorResponse}
 * @throws java.io.IOException if any.
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JsonErrorResponse processValidationError(MethodArgumentNotValidException ex) throws IOException {
    LOGGER.warn("Validation error : {}", ex.getMessage());
    List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
    List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
    JsonErrorResponse errors = new JsonErrorResponse();
    for (FieldError fieldError : fieldErrors) {
        errors.addFieldError(fieldError.getField(), fieldError.getDefaultMessage());
    }
    for (ObjectError globalError : globalErrors) {
        errors.addGlobalError(globalError.getObjectName(), globalError.getDefaultMessage());
    }
    return errors;
}

From source file:com.github.ukase.web.UkaseController.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody// w  ww  .jav  a2 s.  c  o  m
public ResponseEntity<List<ValidationError>> handleValidationException(MethodArgumentNotValidException e) {
    List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
    List<ValidationError> mappedErrors = allErrors.stream().map(ValidationError::new)
            .collect(Collectors.toList());
    log.warn("Validation errors: {}", mappedErrors);
    return new ResponseEntity<>(mappedErrors, HttpStatus.BAD_REQUEST);
}

From source file:com.example.todo.api.common.error.RestGlobalExceptionHandler.java

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    ApiError apiError = createApiError(request, "E400");
    for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
        apiError.addDetail(createApiError(request, fieldError, fieldError.getField()));
    }/*from ww w  . j  a v a 2 s . com*/
    for (ObjectError objectError : ex.getBindingResult().getGlobalErrors()) {
        apiError.addDetail(createApiError(request, objectError, objectError.getObjectName()));
    }
    return handleExceptionInternal(ex, apiError, headers, status, request);
}

From source file:net.jkratz.igdb.controller.advice.ErrorController.java

private Map<String, Object> convertConstraintViolation(MethodArgumentNotValidException ex) {
    Map<String, Object> result = Maps.newHashMap();
    for (FieldError error : ex.getBindingResult().getFieldErrors()) {
        result.put(error.getField(), error.getDefaultMessage());
    }/*from  w w  w  . ja  va 2 s . c  om*/
    return result;
}

From source file:org.apereo.openlrs.controllers.xapi.XAPIExceptionHandlerAdvice.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody/*from  www  . ja v  a2s .  c  o m*/
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;
}