@Test public void testMaxAnnotationValidationToReponse(){ val invalidVal = new ClassWithMinMaxAnnotation("12345678911"); Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal))); JSONObject responseEntityJson = new JSONObject(response.getEntity()); assertThat(response.getStatus()).isEqualTo(400); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("code").toString() ).isEqualTo("MAXLENGTH"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("path").toString() ).isEqualTo("#/annotatedVar"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("limit") ).isEqualTo(MAX_VAL); }
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml"}); context.start(); IValidationService validationService = (IValidationService)context.getBean("validationService"); // Error try { ValidationParameter parameter = new ValidationParameter(); validationService.save(parameter); System.out.println("Validation ERROR"); } catch (RpcException e) { // 抛出的是RpcException ConstraintViolationException ve = (ConstraintViolationException) e.getCause(); // 里面嵌了一个ConstraintViolationException Set<ConstraintViolation<?>> violations = ve.getConstraintViolations(); // 可以拿到一个验证错误详细信息的集合 System.out.println(violations); } }
private ResponseProcessor getResponseProcessor(final Exception e) { if (e instanceof ConstraintViolationException) { if(AnnotationUtils.findAnnotation(e.getClass(), BusinessConstraintValidator.class) != null) { return this.getBusinessConstraintValidatorRP(); } return this.getConstraintValidatorRP(); } if (AnnotationUtils.findAnnotation(e.getClass(), MultiBusinessException.class) != null) { return this.getMultiBusinessExceptionRP(); } return this.getBusinessExceptionRP(); }
/** * @param ex {@link ConstraintViolationException} * @return Returns an object with a list of incorrect parameters. */ @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorDTO processValidationError(final ConstraintViolationException ex) { final ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO(); final Set<ConstraintViolation<?>> set = ex.getConstraintViolations(); for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) { ConstraintViolation<?> next = iterator.next(); validationErrorDTO.getFieldErrors() .add(new ErrorFieldDTO(((PathImpl)next.getPropertyPath()).getLeafNode().getName(), next.getMessage())); } return validationErrorDTO; }
@Test public void testPropertyOnRelation() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); task.setName(null); Project project = new Project(); project.setId(2L); project.setName("test"); project.getTasks().add(task); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("tasks[0]", violation.getPropertyPath().toString()); Assert.assertEquals("/data/relationships/tasks/0", violation.getErrorData().getSourcePointer()); } }
/** * Check not valid parameter operation failed. */ @Test public void objectInvalid() { final SystemUser userDto = new SystemUser(); userDto.setLogin(""); try { validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("object"), Arrays.asList(userDto)); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(NotEmpty.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("", error1.getInvalidValue()); Assert.assertEquals("login", error1.getPropertyPath().toString()); } }
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { } Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); } }
@Override @SuppressWarnings("unchecked") public Object invoke(MethodInvocation invocation) throws Throwable { Class<?>[] groups = determineValidationGroups(invocation); if (forExecutablesMethod != null) { Object executableValidator = ReflectionUtils.invokeMethod(forExecutablesMethod, this.validator); Set<ConstraintViolation<?>> result = (Set<ConstraintViolation<?>>) ReflectionUtils.invokeMethod(validateParametersMethod, executableValidator, invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups); if (!result.isEmpty()) { throw new ConstraintViolationException(result); } Object returnValue = invocation.proceed(); result = (Set<ConstraintViolation<?>>) ReflectionUtils.invokeMethod(validateReturnValueMethod, executableValidator, invocation.getThis(), invocation.getMethod(), returnValue, groups); if (!result.isEmpty()) { throw new ConstraintViolationException(result); } return returnValue; } else { return HibernateValidatorDelegate.invokeWithinValidation(invocation, this.validator, groups); } }
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception { String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName); Class<?> methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { } Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(); Method method = clazz.getMethod(methodName, parameterTypes); Object parameterBean = getMethodParameterBean(clazz, method, arguments); if (parameterBean != null) { if (methodClass != null) { violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass)); } else { violations.addAll(validator.validate(parameterBean, Default.class, clazz)); } } for (Object arg : arguments) { validate(violations, arg, clazz, methodClass); } if (violations.size() > 0) { throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); } }
@Test public void testSizeMaxValidationToReponse(){ val invalidVal = new ClassWithSizeAnnotation("12345678911"); Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal))); JSONObject responseEntityJson = new JSONObject(response.getEntity()); assertThat(response.getStatus()).isEqualTo(400); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("code").toString() ).isEqualTo("MAXLENGTH"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("path").toString() ).isEqualTo("#/annotatedVar"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("limit") ).isEqualTo(MAX_VAL); }
@Test public void testResourceObjectValidation() { Project project = new Project(); project.setId(1L); project.setName(ComplexValidator.INVALID_NAME); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{complex.message}", violation.getMessageTemplate()); Assert.assertEquals("", violation.getPropertyPath().toString()); Assert.assertEquals("", violation.getErrorData().getSourcePointer()); } }
@Test public void testNotNullAnnotationValidationToReponse(){ val invalidVal = new ClassWithNotNullAnnotation(null); Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal))); JSONObject responseEntityJson = new JSONObject(response.getEntity()); assertThat(response.getStatus()).isEqualTo(400); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("code").toString() ).isEqualTo("REQUIRED"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .get("path").toString() ).isEqualTo("#/annotatedVar"); assertThat(responseEntityJson .getJSONArray("errors") .getJSONObject(0) .has("limit") ).isFalse(); }
/** * Validates the {@code request} based on its type and returns it or throws a {@code ValidationException} * if any {@link ConstraintViolation} is found. * * @param request the request object to validate * @param <T> request type param * @return The validated request(the same object passed as {@code request}) * @throws ValidationException if any {@link ConstraintViolation} is found */ public static <T extends SafechargeBaseRequest> T validate(T request) throws ValidationException { Set<ConstraintViolation<T>> constraintViolations = validator.validate(request); if (constraintViolations != null && !constraintViolations.isEmpty()) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { sb.append(constraintViolation.getMessage()) .append(" "); } String errorMessage = sb.toString(); if (logger.isDebugEnabled()) { logger.debug(errorMessage); } throw new ConstraintViolationException(constraintViolations); } return request; }
public void editarEventoTipoUsuario(Evento evento, List<Categoria> categoriasEvento, Usuario usuarioQueEdita) throws AgendamlgException, AgendamlgNotFoundException { try { // Se obtiene una lista de Categorias "de verdad" // No es necesario ya que sobre estos objetos no se invoca // una propiedad como la de getEventoList, de ser asi si habria que hacer este paso // como pasa en Evento, que el evento que llega desde el cliente tiene // categoriaList a null y es por ello que hay que obtener desde el entity manager // un evento "de verdad" if (evento.getTipo() < 1 || evento.getTipo() > 3) { throw AgendamlgException.tipoInvalido(evento.getTipo()); } if (usuarioQueEdita.getTipo() == 3 || evento.getCreador().getId().equals(usuarioQueEdita.getId())) { this.actualizarCategoriaEvento(evento, categoriasEvento); } else { throw AgendamlgException.sinPermisos(usuarioQueEdita.getNombre()); } } catch (ConstraintViolationException e) { throw AgendamlgException.eventoCamposInvalidos(e); } }
/** * Check validation errors success for collections. */ @Test public void jsr349CollectionInvalid() { try { final SystemUser userDto = new SystemUser(); userDto.setLogin("junit"); validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Collection"), Arrays.asList(Arrays.asList(userDto, userDto, userDto))); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(Size.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("jsr349Collection.params", error1.getPropertyPath().toString()); } }
/** * Check not valid parameter operation failed. */ @Test public void objectNull() { final SystemUser userDto = null; try { validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("object"), Arrays.asList(userDto)); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("object.param", error1.getPropertyPath().toString()); } }
public void crearEventoTipoUsuario(Evento evento, List<Categoria> categoriasEvento) throws AgendamlgException { try { Usuario usuario = evento.getCreador(); if (evento.getTipo() < 1 || evento.getTipo() > 3) { throw AgendamlgException.tipoInvalido(evento.getTipo()); } if (usuario.getTipo() == 1) { evento.setValidado((short) 0); this.create(evento); this.anadirCategoriaEvento(evento, categoriasEvento); } else if (usuario.getTipo() > 1) { evento.setValidado((short) 1); this.create(evento); this.anadirCategoriaEvento(evento, categoriasEvento); this.enviarCorreoInteresados(evento); } //Tenemos que coger el id del evento que se acaba de añadir (yo no sé si esto es thread safe) } catch (ConstraintViolationException e) { throw AgendamlgException.eventoCamposInvalidos(e); } }
@Test public void testFailedValidation_OpenOrderRequest() { try { SafechargeBaseRequest safechargeRequest = OpenOrderRequest.builder() .addMerchantInfo(invalidMerchantInfo) .addAmount(invalidAmount) .addCurrency(invalidCurrencyCode) .addItem(dummyInvalidItem) .build(); fail(CONSTRAINT_VIOLATION_EXCEPTION_EXPECTED_BUT_OBJECT_CREATION_PASSED_SUCCESSFULLY); } catch (ConstraintViolationException e) { assertEquals(5, e.getConstraintViolations() .size()); } }
@Test public void testPropertyNotNull() { Project project = new Project(); project.setId(1L); project.setName(null); // violation try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("name", violation.getPropertyPath().toString()); Assert.assertNotNull(violation.getMessage()); Assert.assertTrue(violation.getMessage().contains("null")); Assert.assertEquals("/data/attributes/name", violation.getErrorData().getSourcePointer()); } }
@Override protected void handleValidation(final Message message, final Object resourceInstance, final Method method, final List<Object> arguments) { super.handleValidation(message, resourceInstance, method, arguments); // Check each parameter final Set<ConstraintViolation<?>> validationErrors = new HashSet<>(); for (int index = 0; index < arguments.size(); index++) { final Parameter parameter = method.getParameters()[index]; if (hasToBeValidated(parameter)) { // This parameter is a not context, path or query parameter validate(arguments.get(index), method, parameter, index, validationErrors); } } // Check the veto if (!validationErrors.isEmpty()) { message.put(FaultListener.class.getName(), new NoOpFaultListener()); throw new ConstraintViolationException(validationErrors); } }
private boolean handleException(Exception ex, String invokedClass, String invokedMethod ){ if(ex instanceof InvocationTargetException && ex.getCause() instanceof Exception) ex = (Exception) ex.getCause(); log.error("An error occurred during frontier method invocation <"+invokedClass+"."+invokedMethod+">",ex); if(ex instanceof ConstraintViolationException){ ConstraintViolationException violationException = (ConstraintViolationException) ex; handleConstraintViolation(violationException); return true; } requestContext.getResponse().setStatus(500); requestContext.getResponse().setContentType("text/json;charset=UTF8"); requestContext.echo(serializeThrowable(ex)); return true; }
private void handleConstraintViolation(ConstraintViolationException violationException){ Set<ConstraintViolation<?>> violationSet = violationException.getConstraintViolations(); String[] messages = new String[violationSet.size()]; int i = 0; for(ConstraintViolation violation: violationSet){ messages[i] = violation.getMessage(); i++; } Gson gson = appContext.getGsonBuilder().create(); Map details = new HashMap<>(); details.put("messages",messages); Map exception = new HashMap<>(); exception.put("type",ConstraintViolationException.class.getSimpleName()); exception.put("details",details); String resp = gson.toJson(exception); requestContext.getResponse().setStatus(500); requestContext.getResponse().setContentType("text/json;charset=UTF8"); requestContext.echo(resp); }
@ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<List<String>> handleConstraintViolationException(ConstraintViolationException e) { if (e.getMessage() == null) { List<String> constraints = e.getConstraintViolations().stream() .map(constraintViolation -> new StringBuffer() .append("Le champ ") .append(constraintViolation.getPropertyPath().toString()) .append(" ") .append(constraintViolation.getMessage()) .append(" (valeur : ") .append(constraintViolation.getInvalidValue().toString()) .append(")") .toString()) .collect(Collectors.toList()); return new ResponseEntity<>(constraints, HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(Collections.singletonList(e.getMessage()), HttpStatus.BAD_REQUEST); }
@Test public void testMapElementAttributeNotNull() { ProjectData data = new ProjectData(); data.setValue(null); // violation Project project = new Project(); project.setId(1L); project.setName("test"); project.setDataMap(new LinkedHashMap()); project.getDataMap().put("someKey", data); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("dataMap[someKey].value", violation.getPropertyPath().toString()); Assert.assertNotNull(violation.getMessage()); Assert.assertEquals("/data/attributes/dataMap/someKey/value", violation.getErrorData().getSourcePointer()); } }
public T build() throws ConstraintViolationException { T object = buildInternal(); Set<ConstraintViolation<T>> violations = validator.validate(object); if (!violations.isEmpty()) { Set<String> violationMessages = new HashSet<String>(); for (ConstraintViolation<T> constraintViolation : violations) { violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage()); } throw new ConstraintViolationException(violationMessages.toString() , violations); } return object; }
@Test(expected=ConstraintViolationException.class) public void testDevValidation() { Developer developer = new Developer(); DeveloperInfo developerInfo = new DeveloperInfo(); developer.setId("alovelace"); developerInfo.setFirstName("Ada"); developerInfo.setLastName("Lovelace"); developer.setDeveloperInfo(developerInfo); developerRepository.save(developer); }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirCodMunicipioTamanhoInvalido() throws Exception { try { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comDiscriminacao("Descricao Teste") .comCodigoMunicipio("") .build(); } catch (final ConstraintViolationException e) { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comDiscriminacao("Descricao Teste") .comCodigoMunicipio("31062005") .build(); } }
public Response toResponse(RpcException e) { // TODO do more sophisticated exception handling and output if (e.getCause() instanceof ConstraintViolationException) { return handleConstraintViolationException((ConstraintViolationException) e.getCause()); } // we may want to avoid exposing the dubbo exception details to certain clients // TODO for now just do plain text output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal server error: " + e.getMessage()).type(ContentType.TEXT_PLAIN_UTF_8).build(); }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirServicoSemDiscriminacao() throws Exception { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comCodigoCnae("0000000") .comCodigoTributacaoMunicipio("00000000000000000000") .comCodigoMunicipio("3106200") .build(); }
/** * 为参数验证添加异常处理器 */ @ExceptionHandler(ConstraintViolationException.class) public RestResult handleConstraintViolationException(ConstraintViolationException cve) { //这里简化处理了,cve.getConstraintViolations 会得到所有错误信息的迭代,可以酌情处理 String errorMessage = cve.getConstraintViolations().iterator().next().getMessage(); return generator.getFailResult(errorMessage); }
/** * Handle validation exceptions. */ @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity handleConstraintViolationException(final ConstraintViolationException e) { final StringBuilder builder = new StringBuilder(); e.getConstraintViolations().forEach(violation -> builder.append( String.format("%s Current value: %s", violation.getMessage(), violation.getInvalidValue()))); log.warn(builder.toString()); return ResponseEntity.badRequest().body(new ErrorDto(builder.toString())); }
@ExceptionHandler(ConstraintViolationException.class) @ResponseBody public ErrorRes constraintViolationExceptionHandler(HttpServletResponse response, ConstraintViolationException e) { response.setStatus(400); Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); if (!violations.isEmpty()) { ConstraintViolation<?> violation = violations.iterator().next(); return new ErrorRes(-1, violation.getPropertyPath().toString() + violation.getMessage()); } return new ErrorRes(); }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirBairroComTamanhoInvalido() throws Exception { try { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comBairro("").build(); } catch (final ConstraintViolationException e) { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comBairro("DcifpaAuHvgeappsWffEdIQdPLLxmQnoyDJQyMRiLLjgUcpOZncjZNBkaqDjf").build(); } }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirCodigoMunicipioComTamanhoInvalido() throws Exception { try { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comCodigoMunicipio("").build(); } catch (final ConstraintViolationException e) { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comCodigoMunicipio("00000000").build(); } }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirUfComTamanhoInvalido() throws Exception { try { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comUf("").build(); } catch (final ConstraintViolationException e) { FabricaDeObjetosFake.getTomadorEnderecoBuilder() .comUf("AAA").build(); } }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirDocumentoComTamanhoInvalido() throws Exception { try { new TomadorCpfCnpjBuilder().comDocumento("1234567890").build(); } catch (final ConstraintViolationException e) { new TomadorCpfCnpjBuilder().comDocumento("123456789090").build(); } }
@ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<ErrorResponse> handle(ConstraintViolationException e) { ErrorResponse errors = new ErrorResponse(); e.getConstraintViolations().forEach(constraintViolation -> { ErrorItem errorItem = new ErrorItem(); errorItem.setCode(constraintViolation.getMessageTemplate()); errorItem.setMessage(constraintViolation.getMessage()); errors.addError(errorItem); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirDocumentoComPontuacao() throws Exception { try { new TomadorCpfCnpjBuilder().comDocumento("123.456.789-09").build(); } catch (final ConstraintViolationException e) { new TomadorCpfCnpjBuilder().comDocumento("12.548.785/9856-42").build(); } }
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirDocumentoInvalido() throws Exception { try { new TomadorCpfCnpjBuilder().comDocumento("11111111112").build(); } catch (final ConstraintViolationException e) { new TomadorCpfCnpjBuilder().comDocumento("11111111111112").build(); } }
@ResponseBody @ResponseStatus(HttpStatus.OK) @ExceptionHandler({ConstraintViolationException.class}) public Map<String, String> handleException(ConstraintViolationException e) { StringBuilder message = new StringBuilder(); for (ConstraintViolation<?> s : e.getConstraintViolations()) { message.append(s.getMessage()).append(" "); } log.warn("参数校验失败: {}", message.toString()); return ImmutableMap.of("code", "1911001", "message", message.toString()); }