org.springframework.validation.FieldError Java Examples
The following examples show how to use
org.springframework.validation.FieldError.
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
Source File: EscapedErrors.java From spring-analysis-note with MIT License | 6 votes |
@SuppressWarnings("unchecked") @Nullable private <T extends ObjectError> T escapeObjectError(@Nullable T source) { if (source == null) { return null; } String defaultMessage = source.getDefaultMessage(); if (defaultMessage != null) { defaultMessage = HtmlUtils.htmlEscape(defaultMessage); } if (source instanceof FieldError) { FieldError fieldError = (FieldError) source; Object value = fieldError.getRejectedValue(); if (value instanceof String) { value = HtmlUtils.htmlEscape((String) value); } return (T) new FieldError( fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), defaultMessage); } else { return (T) new ObjectError( source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage); } }
Example #2
Source File: SpringValidatorAdapterTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-13406 public void testNoStringArgumentValue() { TestBean testBean = new TestBean(); testBean.setPassword("pass"); testBean.setConfirmPassword("pass"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldValue("password"), is("pass")); FieldError error = errors.getFieldError("password"); assertNotNull(error); assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128")); assertTrue(error.contains(ConstraintViolation.class)); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); }
Example #3
Source File: ValidatorFactoryTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void testSpringValidationWithErrorInSetElement() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(3, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); fieldError = result.getFieldError("addressSet[].street"); assertEquals("addressSet[].street", fieldError.getField()); }
Example #4
Source File: BindingResultAspect.java From BigDataPlatform with GNU General Public License v3.0 | 6 votes |
@Around("BindingResult()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); for (Object arg : args) { if (arg instanceof BindingResult) { BindingResult result = (BindingResult) arg; if (result.hasErrors()) { FieldError fieldError = result.getFieldError(); if (fieldError != null) { return CommonResult.validateFailed(fieldError.getDefaultMessage()); } else { return CommonResult.validateFailed(); } } } } return joinPoint.proceed(); }
Example #5
Source File: RestExceptionTranslator.java From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 | 6 votes |
/** * Handle validation errors * * @return validation error with the fields errors and a bad request */ @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public RestFieldsErrorsDto handleValidationExceptions(MethodArgumentNotValidException exception) { BindingResult result = exception.getBindingResult(); String errorCode = RestErrorConstants.ERR_VALIDATION_ERROR; LOGGER.error(ERROR_MSG, errorCode, exception); RestFieldsErrorsDto restFieldsErrors = new RestFieldsErrorsDto(errorCode, getLocalizedMessageFromErrorCode(errorCode)); List<FieldError> fieldErrors = result.getFieldErrors(); fieldErrors.forEach(fieldError -> restFieldsErrors.addError(new RestFieldErrorDto(fieldError.getField(), fieldError.getCode(), getLocalizedMessageFromFieldError(fieldError)))); return restFieldsErrors; }
Example #6
Source File: BindingResultErrorUtils.java From faster-framework-project with Apache License 2.0 | 6 votes |
/** * @param bindingResult bindingResult * @return bindingResult错误内容 */ public static String resolveErrorMessage(BindingResult bindingResult) { if (bindingResult == null || CollectionUtils.isEmpty(bindingResult.getFieldErrors())) { return ""; } StringBuilder errorMsg = new StringBuilder(); List<FieldError> fieldErrorList = bindingResult.getFieldErrors(); for (FieldError fieldError : fieldErrorList) { errorMsg.append("[") .append(fieldError.getField()) .append(":") .append(fieldError.getDefaultMessage()) .append("]"); } return errorMsg.toString(); }
Example #7
Source File: PetControllerExceptionHandler.java From api-layer with Eclipse Public License 2.0 | 6 votes |
/** * The handleMethodArgumentNotValid method creates a response with a list of messages that contains the fields with errors * * @param exception MethodArgumentNotValidException * @return 400 and a list of messages with invalid fields */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ApiMessageView> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) { List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors(); List<Object[]> messages = new ArrayList<>(); for (FieldError fieldError : fieldErrors) { Object[] messageFields = new Object[3]; messageFields[0] = fieldError.getField(); messageFields[1] = fieldError.getRejectedValue(); messageFields[2] = fieldError.getDefaultMessage(); messages.add(messageFields); } List<ApiMessage> listApiMessage = messageService .createMessage("org.zowe.apiml.sampleservice.api.petMethodArgumentNotValid", messages) .stream() .map(Message::mapToApiMessage) .collect(Collectors.toList()); return ResponseEntity .status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON_UTF8) .body(new ApiMessageView(listApiMessage)); }
Example #8
Source File: CheckUtil.java From api-mock-util with Apache License 2.0 | 6 votes |
/** * 校验model上的注解 * * @param pjp 连接点 */ public static void checkModel(ProceedingJoinPoint pjp) { StringBuilder sb = new StringBuilder(); try { //找到BindingResult参数 List<BindingResult> results = getBindingResult(pjp); if (results != null && !results.isEmpty()) { for (BindingResult result : results) { if (null != result && result.hasErrors()) { //拼接错误信息 if (null != result.getFieldErrors()) { for (FieldError fe : result.getFieldErrors()) { sb.append(fe.getField() + "-" + fe.getDefaultMessage()).append(" "); } } } } if (StringUtils.isNotBlank(sb.toString())) { fail(sb.toString());//抛出检查异常 } } } catch (Exception e) { fail(e.getMessage());//抛出检查异常 } }
Example #9
Source File: SpringValidatorAdapterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-13406 public void testNoStringArgumentValue() { TestBean testBean = new TestBean(); testBean.setPassword("pass"); testBean.setConfirmPassword("pass"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldValue("password"), is("pass")); FieldError error = errors.getFieldError("password"); assertNotNull(error); assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128")); assertTrue(error.contains(ConstraintViolation.class)); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); }
Example #10
Source File: ValidationBindingResult.java From onetwo with Apache License 2.0 | 6 votes |
public String getFieldErrorMessage(FieldError fe, boolean readFieldMeta){ if(fe==null){ // throw new JFishException("can not find this field named : " + fieldName); return ""; } String fmsg = null; if(readFieldMeta){ JFishProperty jp = JFishPropertyFactory.create(getTarget().getClass(), fe.getField(), true); if(jp==null) jp = JFishPropertyFactory.create(getTarget().getClass(), fe.getField(), false); FieldName jfm = jp.getAnnotation(FieldName.class); if(jfm==null){ fmsg = LangUtils.append(fe.getField(), fe.getDefaultMessage()); }else{ fmsg = LangUtils.append(jfm.value(), fe.getDefaultMessage()); } }else{ fmsg = fe.getDefaultMessage(); } return fmsg; }
Example #11
Source File: SpringValidatorAdapterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-13406 public void testApplyMessageSourceResolvableToStringArgumentValueWithResolvedLogicalFieldName() { TestBean testBean = new TestBean(); testBean.setPassword("password"); testBean.setConfirmPassword("PASSWORD"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("password"), is(1)); assertThat(errors.getFieldValue("password"), is("password")); FieldError error = errors.getFieldError("password"); assertNotNull(error); assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Password must be same value as Password(Confirm)")); assertTrue(error.contains(ConstraintViolation.class)); assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password")); }
Example #12
Source File: ValidatorFactoryTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testSpringValidationWithErrorInSetElement() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(3, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); fieldError = result.getFieldError("addressSet[].street"); assertEquals("addressSet[].street", fieldError.getField()); }
Example #13
Source File: DefaultExceptionAdvice.java From momo-cloud-permission with Apache License 2.0 | 6 votes |
/** * 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 #14
Source File: CodeGenExceptionHandler.java From das with Apache License 2.0 | 6 votes |
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 #15
Source File: ValidatorFactoryTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(2, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); List<String> errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(4, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.name")); assertTrue(errorCodes.contains("NotNull.name")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(5, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.address.street")); assertTrue(errorCodes.contains("NotNull.address.street")); assertTrue(errorCodes.contains("NotNull.street")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); }
Example #16
Source File: SystemExceptionHandler.java From codeway_service with GNU General Public License v3.0 | 6 votes |
/** * 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 #17
Source File: JsonResult.java From match-trade with Apache License 2.0 | 6 votes |
/** * <p>返回失败,无数据</p> * @param BindingResult * @return JsonResult */ public JsonResult<T> error(BindingResult result, MessageSource messageSource) { StringBuffer msg = new StringBuffer(); // 获取错位字段集合 List<FieldError> fieldErrors = result.getFieldErrors(); // 获取本地locale,zh_CN Locale currentLocale = LocaleContextHolder.getLocale(); for (FieldError fieldError : fieldErrors) { // 获取错误信息 String errorMessage = messageSource.getMessage(fieldError, currentLocale); // 添加到错误消息集合内 msg.append(fieldError.getField() + ":" + errorMessage + " "); } this.setCode(CODE_FAILED); this.setMsg(msg.toString()); this.setData(null); return this; }
Example #18
Source File: LogicAdvice.java From api-boot with Apache License 2.0 | 5 votes |
/** * 根据错误字段对象获取错误消息 * * @param fieldError 错误字段对象 * @return */ String resolveLocalErrorMessage(FieldError fieldError) { //获取本地locale,zh_CN Locale currentLocale = LocaleContextHolder.getLocale(); //返回错误信息 return messageSource.getMessage(fieldError, currentLocale); }
Example #19
Source File: ExceptionTranslator.java From flair-registry with Apache License 2.0 | 5 votes |
@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; }
Example #20
Source File: BaseController.java From spring-boot-demo-all with Apache License 2.0 | 5 votes |
protected String validatedError(BindingResult result) { List<AjaxResult> errorList = new ArrayList<AjaxResult>(); for (FieldError error : result.getFieldErrors()) { AjaxResult errorResult = new AjaxResult(); errorResult.setCode(error.getField()); errorResult.setMessage(error.getDefaultMessage()); errorList.add(errorResult); } return JSONObject.toJSONString(errorList); }
Example #21
Source File: ApiError.java From spring-glee-o-meter with GNU General Public License v3.0 | 5 votes |
private void addValidationError(FieldError fieldError) { this.addValidationError( fieldError.getObjectName(), fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage()); }
Example #22
Source File: GlobalExceptionHandler.java From spring-boot-plus with Apache License 2.0 | 5 votes |
/** * 非法参数验证异常 * * @param ex * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.OK) public ApiResult<List<String>> handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) { printRequestDetail(); BindingResult bindingResult = ex.getBindingResult(); List<String> list = new ArrayList<>(); List<FieldError> fieldErrors = bindingResult.getFieldErrors(); for (FieldError fieldError : fieldErrors) { list.add(fieldError.getDefaultMessage()); } Collections.sort(list); log.error(getApiCodeString(ApiCode.PARAMETER_EXCEPTION) + ":" + JSON.toJSONString(list)); return ApiResult.fail(ApiCode.PARAMETER_EXCEPTION, list); }
Example #23
Source File: BaseExceptionHandler.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
/** * 统一处理请求参数校验(json) * * @param e ConstraintViolationException * @return FebsResponse */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public FebsResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) { StringBuilder message = new StringBuilder(); for (FieldError error : e.getBindingResult().getFieldErrors()) { message.append(error.getField()).append(error.getDefaultMessage()).append(StringConstant.COMMA); } message = new StringBuilder(message.substring(0, message.length() - 1)); log.error(message.toString()); return new FebsResponse().message(message.toString()); }
Example #24
Source File: BaseExceptionHandler.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
/** * 统一处理请求参数校验(实体对象传参) * * @param e BindException * @return FebsResponse */ @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public FebsResponse handleBindException(BindException e) { StringBuilder message = new StringBuilder(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); for (FieldError error : fieldErrors) { message.append(error.getField()).append(error.getDefaultMessage()).append(StringConstant.COMMA); } message = new StringBuilder(message.substring(0, message.length() - 1)); log.error(message.toString()); return new FebsResponse().message(message.toString()); }
Example #25
Source File: ExceptionHandle.java From uexam-mysql with GNU Affero General Public License v3.0 | 5 votes |
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public RestResponse handler(MethodArgumentNotValidException e) { String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> { FieldError fieldError = (FieldError) file; return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage()); }).collect(Collectors.joining()); return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg); }
Example #26
Source File: UniformHandler.java From Milkomeda with MIT License | 5 votes |
/** * 处理Bean校验异常 * @param ex 异常 * @param bindingResult 错误绑定数据 * @return ResponseEntity */ private ResponseEntity<Object> handleValidBeanExceptionResponse(Exception ex, BindingResult bindingResult) { ObjectError objectError = bindingResult.getAllErrors().get(0); String message = objectError.getDefaultMessage(); if (objectError.getArguments() != null && objectError.getArguments().length > 0) { FieldError fieldError = (FieldError) objectError; message = WebContext.getRequest().getRequestURI() + " [" + fieldError.getField() + "=" + fieldError.getRejectedValue() + "] " + message; } log.warn("Hydrogen uniform valid response exception with msg: {} ", message); return handleExceptionResponse(ex, HttpStatus.BAD_REQUEST.value(), message); }
Example #27
Source File: RestErrorHandler.java From metamodel-membrane with Apache License 2.0 | 5 votes |
/** * 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; }
Example #28
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java From backstopper with Apache License 2.0 | 5 votes |
@Test public void shouldHandleException_handles_WebExchangeBindException_as_expected() { // given BindingResult bindingResult = mock(BindingResult.class); ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError(); ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError(); ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError(); List<ObjectError> errorsList = Arrays.asList( new FieldError("someObj", "someField", someFieldError.getName()), new FieldError("otherObj", "otherField", otherFieldError.getName()), new ObjectError("notAFieldObject", notAFieldError.getName()) ); when(bindingResult.getAllErrors()).thenReturn(errorsList); WebExchangeBindException ex = new WebExchangeBindException(null, bindingResult); // when ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); // then validateResponse(result, true, Arrays.asList( new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")), new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")), notAFieldError )); verify(bindingResult).getAllErrors(); }
Example #29
Source File: ErrorHalRepresentationFactoryTest.java From edison-microservice with Apache License 2.0 | 5 votes |
@Test public void shouldBuildRepresentationForValidationResults() { // given final ErrorHalRepresentationFactory factory = new ErrorHalRepresentationFactory(messageSource, new ObjectMapper(), "someErrorProfile"); // when final Errors mockErrors = mock(Errors.class); final FieldError fieldError = new FieldError("someObject", "xyzField", "rejected", true, new String[]{"NotEmpty"}, new Object[]{}, "Some default message"); when(mockErrors.getAllErrors()).thenReturn(Collections.singletonList(fieldError)); when(mockErrors.getErrorCount()).thenReturn(1); final ErrorHalRepresentation errorHalRepresentation = factory.halRepresentationForValidationErrors(mockErrors); // then assertThat(errorHalRepresentation.getErrorMessage(), is("Validation failed. 1 error(s)")); assertThat(errorHalRepresentation.getLinks().getLinkBy("profile").isPresent(), is(true)); assertThat(errorHalRepresentation.getLinks().getLinkBy("profile").get().getHref(), is("someErrorProfile")); final List<Map<String, String>> listOfViolations = errorHalRepresentation.getErrors().get("xyzField"); assertThat(listOfViolations, hasSize(1)); assertThat(listOfViolations.get(0), hasEntry("key", "text.not_empty")); assertThat(listOfViolations.get(0), hasEntry("message", "Some default message")); assertThat(listOfViolations.get(0), hasEntry("rejected", "rejected")); }
Example #30
Source File: BaseController.java From roncoo-education with MIT License | 5 votes |
/** * 错误提示,不关闭当前对话框,自定义提示信息 * * @param message * 提示信息 * @return */ protected static String error(BindingResult bindingResult) { StringBuilder sb = new StringBuilder(); for (FieldError fieldError : bindingResult.getFieldErrors()) { sb.append(fieldError.getDefaultMessage()).append("<br/>"); } return error(sb.toString()); }