Java Code Examples for org.springframework.web.bind.MethodArgumentNotValidException

The following examples show how to use org.springframework.web.bind.MethodArgumentNotValidException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
@Parameters(method = "provideValidationParams")
public void validationException_ShouldBeHandledProperly(Object pojo, Locale locale, CodedMessage... codedMessages) {
    contextRunner.run(ctx -> {
        WebErrorHandlers errorHandlers = ctx.getBean(WebErrorHandlers.class);
        Validator validator = ctx.getBean(Validator.class);

        BindingResult result = new BeanPropertyBindingResult(pojo, "pojo");
        validator.validate(pojo, result);

        // Assertions for BindException
        HttpError bindError = errorHandlers.handle(new BindException(result), null, locale);
        assertThat(bindError.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
        assertThat(bindError.getErrors()).containsOnly(codedMessages);

        // Assertions for MethodArgumentNotValidException
        HttpError argumentError = errorHandlers.handle(new MethodArgumentNotValidException(mock(MethodParameter.class), result), null, locale);
        assertThat(argumentError.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
        assertThat(argumentError.getErrors()).containsOnly(codedMessages);

        verifyPostProcessorsHasBeenCalled(ctx);
    });
}
 
Example 2
Source Project: spring-boot   Source File: CustomGlobalExceptionHandler.java    License: MIT License 7 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                              HttpHeaders headers,
                                                              HttpStatus status, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", new Date());
    body.put("status", status.value());

    //Get all errors
    List<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(x -> x.getDefaultMessage())
            .collect(Collectors.toList());

    body.put("errors", errors);

    return new ResponseEntity<>(body, headers, status);

    //Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect(
    //        Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

}
 
Example 3
@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);
}
 
Example 4
Source Project: http-patch-spring   Source File: WebApiExceptionHandler.java    License: MIT License 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                              HttpHeaders headers, HttpStatus status,
                                                              WebRequest request) {

    List<String> globalErrors = ex.getBindingResult().getGlobalErrors()
            .stream()
            .map(error -> error.getObjectName() + ": " + error.getDefaultMessage())
            .collect(toList());

    List<ApiResourcePropertyError> fieldErrors = ex.getBindingResult().getFieldErrors()
            .stream()
            .map(this::toResourcePropertyError)
            .collect(toList());

    ApiError apiError = ApiError.builder()
            .message("Validation error")
            .status(ex.getParameter().hasParameterAnnotation(RequestBody.class) ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.BAD_REQUEST)
            .details(Stream.concat(globalErrors.stream(), fieldErrors.stream()).collect(toList()))
            .build();

    return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
 
Example 5
Source Project: das   Source File: CodeGenExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
private Object exeute(HttpServletRequest reqest, HttpServletResponse response, Exception e) {
    log.error(StringUtil.getMessage(e), e);
    //if (isAjax(reqest)) {
    String exMsg = StringUtil.getMessage(e);
    if (e instanceof InvocationTargetException && exMsg == null) {
        exMsg = ((InvocationTargetException) e).getTargetException().getMessage();
    } else if (e instanceof MethodArgumentNotValidException) {
        List<String> list = StringUtil.toList(exMsg, "default message");
        if (CollectionUtils.isNotEmpty(list) && list.size() > 1) {
            List<FieldError> errors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
            if (CollectionUtils.isNotEmpty(list)) {
                exMsg = errors.get(0).getDefaultMessage();
            }
        }
    }
    if (exMsg == null) {
        exMsg = e.toString();
    }
    return ServiceResult.fail(exMsg);
   /* } else {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/err/500/index.html");
        return modelAndView;
    }*/
}
 
Example 6
@Test
@Parameters(method = "provideParamsForHandle")
public void handle_ShouldHandleTheValidationErrorsProperly(Object toValidate,
                                                           Set<String> errorCodes,
                                                           Map<String, List<Argument>> args) {
    BindingResult result = new BeanPropertyBindingResult(toValidate, "toValidate");
    validator.validate(toValidate, result);

    // Create and assert for BindException

    BindException bindException = new BindException(result);
    HandledException handledForBind = handler.handle(bindException);

    assertThat(handledForBind.getErrorCodes()).containsAll(errorCodes);
    assertThat(handledForBind.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    assertThat(handledForBind.getArguments()).isEqualTo(args);

    // Create and assert for MethodArgumentNotValidException

    MethodArgumentNotValidException exception = new MethodArgumentNotValidException(null, result);
    HandledException handled = handler.handle(exception);

    assertThat(handled.getErrorCodes()).containsAll(errorCodes);
    assertThat(handled.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
    assertThat(handled.getArguments()).isEqualTo(args);
}
 
Example 7
@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);
}
 
Example 8
@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);
}
 
Example 9
Source Project: flair-registry   Source File: ExceptionTranslatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 10
/**
 * JSR303参数校验错误
 * @param ex BindException
 */
@ExceptionHandler({BindException.class,MethodArgumentNotValidException.class})
public JsonData<Void> bindException(MethodArgumentNotValidException ex) {
	LogBack.error(ex.getMessage(), ex);
	BindingResult bindingResult = ex.getBindingResult();
	if (bindingResult.hasErrors()) {
		List<FieldError> errors = bindingResult.getFieldErrors();
		List<ValidFieldError> validList = new ArrayList<>();
		if (!(CollectionUtils.isEmpty(errors))) {
			for (FieldError fe : errors) {
				validList.add(new ValidFieldError(fe));
			}
		}
		LogBack.error("参数校验错误:" + validList.toString(), ex);
		return JsonData.failed(StatusEnum.PARAM_INVALID, validList.toString());
	}
	return JsonData.failed(StatusEnum.PARAM_INVALID);
}
 
Example 11
Source Project: spring-boot   Source File: CustomGlobalExceptionHandler.java    License: MIT License 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                              HttpHeaders headers,
                                                              HttpStatus status, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", new Date());
    body.put("status", status.value());

    //Get all errors
    List<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(x -> x.getDefaultMessage())
            .collect(Collectors.toList());

    body.put("errors", errors);

    return new ResponseEntity<>(body, headers, status);

    //Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect(
    //        Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

}
 
Example 12
Source Project: TeamDojo   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 13
Source Project: White-Jotter   Source File: DefaultExceptionHandler.java    License: MIT License 6 votes vote down vote up
@ExceptionHandler(value = Exception.class)
public Result exceptionHandler(Exception e) {
    String message = null;

    if (e instanceof IllegalArgumentException) {
        message = "传入了错误的参数";
    }

    if (e instanceof MethodArgumentNotValidException) {
        message = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
    }

    if (e instanceof UnauthorizedException) {
        message = "权限认证失败";
    }

    return ResultFactory.buildFailResult(message);
}
 
Example 14
/**
 * IllegalArgumentException异常处理返回json
 * 返回状态码:500
 */
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({MethodArgumentNotValidException.class})
public JSONResult argumentNotValidException(MethodArgumentNotValidException e) {
    List<FieldError> bindingResult = e.getBindingResult().getFieldErrors();
    StringBuilder sb = new StringBuilder();
    //请求参数错误
    sb.append(ErrorEnum.ERROR_PARAM.getErrorMessage()).append(" --> ");
    for (FieldError fieldError : bindingResult) {
        sb.append(fieldError.getField());
        sb.append(" : ");
        sb.append(fieldError.getDefaultMessage());
        sb.append(" ; ");
    }

    return defHandler(null, sb.toString(), e);
}
 
Example 15
Source Project: alchemy   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 16
@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_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 17
@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_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 18
@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_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example 19
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 20
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 21
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 22
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 23
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 24
@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);
}
 
Example 25
@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);
}
 
Example 26
Source Project: cubeai   Source File: ExceptionTranslator.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 27
Source Project: AnyMock   Source File: HttpExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public DataResponse<List<FieldErrorDTO>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    DataResponse<List<FieldErrorDTO>> response
            = new DataResponse<>(translator.translate(ResultCode.ILLEGAL_ARGUMENT));

    BindingResult bindingResult = e.getBindingResult();
    if (bindingResult.hasErrors()) {
        List<FieldErrorDTO> fieldErrorDTOList = new LinkedList<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            FieldErrorDTO fieldErrorDTO = new FieldErrorDTO();
            fieldErrorDTO.setField(fieldError.getField());
            fieldErrorDTO.setErrorInfo(fieldError.getDefaultMessage());
            fieldErrorDTOList.add(fieldErrorDTO);
        });
        response.setData(fieldErrorDTOList);
    }
    logger.warn("{}", response, e);
    return response;
}
 
Example 28
@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);
}
 
Example 29
/**
 * 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);
}
 
Example 30
Source Project: sk-admin   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 处理所有接口数据验证异常
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    // 打印堆栈信息
    log.error(ThrowableUtil.getStackTrace(e));
    String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
    String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
    String msg = "不能为空";
    if (msg.equals(message)) {
        message = str[1] + ":" + message;
    }
    return buildResponseEntity(ApiError.error(message));
}