public async Task ResourceValidationExceptionShouldReturnExpectedCode( SampleServerFactory serverFactory, Mock <IExceptionService> exceptionService, string code, string message, string entityType, string entityId, string errorMessage) { var expectedErrors = new List <ValidationError> { new ValidationError(entityType, entityId, ValidationErrorCode.Invalid, errorMessage) }; var thrownException = new EntityValidationException(new ValidationErrorDetails(message, expectedErrors)); exceptionService.Setup(s => s.Execute()).Throws(thrownException); using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create()) { var response = await server.HttpClient.GetAsync("/"); try { await response.HandleErrors(); } catch (EntityValidationException exception) { Assert.Equal("AR422", exception.Event.Code); } } }
public async Task ResourceValidationExceptionShouldIncludeExpectedErrors( SampleServerFactory serverFactory, Mock <IExceptionService> exceptionService, string code, string message, string errorMessage) { var expectedErrors = new List <ValidationError> { new ValidationError("EntityType", "EntityId", ValidationErrorCode.Invalid, errorMessage) }; var thrownException = new EntityValidationException(code, new ValidationErrorDetails(message, expectedErrors)); exceptionService.Setup(s => s.Execute()).Throws(thrownException); using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create()) { var response = await server.HttpClient.GetAsync("/"); try { await response.HandleErrors(); } catch (EntityValidationException exception) { var errors = exception.Event?.ErrorDetails?.Errors; errors.Should().BeEquivalentTo(expectedErrors); } } }
public void DadoUmFornecedorPFMenorDeIdade_AoCadastrarFornecedorNumaEmpresaDoParana_DeveImpedirOCadastro() { DadoUmFornecedorPFMenorDeIdade(); EntityValidationException ex = Assert.Throws <EntityValidationException>(() => AoCadastrarFornecedor()); ex.Erros[0].Should().Be("Fornecedores do Paraná devem ser maiores de idade."); ex.Message.Should().Be("Entidade inválida"); }
public void DadoUmFornecedorPFSemRgEDataDeNascimento_AoCadastrarFornecedor_DeveImpedirOCadastro() { DadoUmFornecedorPFSemRgEDataDeNascimento(); EntityValidationException ex = Assert.Throws <EntityValidationException>(() => AoCadastrarFornecedor()); ex.Erros[0].Should().Be("O campo RG de fornecedor deve deve ter entre 5 e 11 números."); ex.Erros[1].Should().Be("A data de nascimento é obrigatória para pessoa física."); ex.Message.Should().Be("Entidade inválida"); }
public void Validate(T entity) { EntityValidationException <T> exception = null; if (this.exceptionQueue.TryDequeue(out exception)) { throw exception; } throw new InvalidOperationException("Fake queue was empty"); }
public async Task ResourceValidationResponseShouldThrowValidationException( SampleServerFactory serverFactory, Mock <IExceptionService> exceptionService, EntityValidationException exception) { exceptionService.Setup(s => s.Execute()).Throws(exception); using (var server = serverFactory.With <IExceptionService>(exceptionService.Object).Create()) { var response = await server.HttpClient.GetAsync("/"); await Assert.ThrowsAsync <EntityValidationException>(() => response.HandleErrors()); } }
private void PrepareEFException(Exception exSource) { if (exSource is DbUpdateConcurrencyException) { var ex2 = exSource as DbUpdateConcurrencyException; var newEx = new UpdateConcurrencyException( ex2.Message, ex2.InnerException, ex2.Entries.Select(x => new RepositoryEntryInternal(x))); throw newEx; } else if (exSource is DbUpdateException) { var ex2 = exSource as DbUpdateConcurrencyException; if (ex2 != null) { var newEx = new UpdateException( ex2.Message, ex2.InnerException, ex2.Entries.Select(x => new RepositoryEntryInternal(x))); throw newEx; } else { var newEx = new UpdateException( exSource.Message, exSource.InnerException, null); throw newEx; } } else if (exSource is System.Data.Entity.Validation.DbEntityValidationException) { var ex2 = exSource as System.Data.Entity.Validation.DbEntityValidationException; var newEx = new EntityValidationException( ex2.Message, ex2.EntityValidationErrors.Select(x => new EntityValidationResult(new RepositoryEntryInternal(x.Entry), x.ValidationErrors.Select(y => new ValidationError(y.PropertyName, y.ErrorMessage)))), ex2.InnerException ); throw newEx; } }
public async Task OwinExceptionShouldInvokeLogger( SampleServerFactory serverFactory, Mock <IExceptionService> exceptionService, EntityValidationException exception, Mock <IAutoResponseLogger> logger) { logger.Setup(l => l.LogException(It.IsAny <Exception>())).Returns(Task.FromResult(0)); exceptionService.Setup(s => s.Execute()).Throws(exception); using (var server = serverFactory .With <IExceptionService>(exceptionService.Object) .With <IAutoResponseLogger>(logger.Object) .Create()) { await server.HttpClient.GetAsync("/"); logger.Verify(l => l.LogException(It.IsAny <Exception>()), Times.Once()); } }
public static ServiceBadRequest GetValidationProblemDetails(EntityValidationException ex) { Dictionary <string, string[]> errors = new Dictionary <string, string[]>(); var results = ex.Validation; var members = results.SelectMany(r => r.MemberNames); foreach (var member in members) { List <string> errMessages = new List <string>(); foreach (var error in results.Where(r => r.MemberNames.Contains(member))) { errMessages.Add(error.ErrorMessage); } errors.Add(member, errMessages.ToArray()); } ServiceBadRequest details = new ServiceBadRequest(errors); return(details); }
/// <summary> /// 提交当前单元操作的结果 /// </summary> /// <returns></returns> public int Commit() { if (IsCommitted) { return(0); } try { int result = Context.SaveChanges(); IsCommitted = true; return(result); } catch (Exception ex) { var entities = from entity in Context.ChangeTracker.Entries() where entity.State == EntityState.Added || entity.State == EntityState.Modified || entity.State == EntityState.Deleted select entity.Entity; var validationResults = new List <ValidationResult>(); foreach (var entity in entities) { var validationContext = new ValidationContext(entity); Validator.TryValidateObject(entity, validationContext, validationResults); } EntityValidationException validationException = new EntityValidationException(validationResults.Select(x => new ValidationException(x, null, null))); StringBuilder sbErrors = new StringBuilder(); foreach (var err in validationException.ValidationErrors) { var validationResult = err.ValidationResult; sbErrors.Append("Error: " + validationResult.MemberNames.First() + ", Message: " + validationResult.ErrorMessage + Environment.NewLine); } throw PublicHelper.ThrowDataAccessException("提交数据验证时发生异常:" + sbErrors, ex); } }
public void EntityValidationExceptionLogRegister() { var validationResults = new List <ValidationResult> { new ValidationResult("Name not empty", new List <string> { "Name" }), new ValidationResult("Id not empty", new List <string> { "Id" }) }; var entityValidationException = new EntityValidationException(validationResults); GivenRequiredService().Log(entityValidationException); var ex = TestLog.GetException(); ex[0].Should().BeOfType <ValidationException>(); ex[0].As <ValidationException>().Message.Should().Be("Name not empty"); ex[1].Should().BeOfType <ValidationException>(); ex[1].As <ValidationException>().Message.Should().Be("Id not empty"); }
public FakeEntityValidator <T> WithValidationMessage(string message) { this.exception = new EntityValidationException <T>(message); return(this); }
public void ErrorMessageIsPopulated() { var ex = new EntityValidationException("msg"); Assert.AreEqual("msg", ex.Message); }
public static void AddValidationErrors(this ModelStateDictionary modelState, EntityValidationException exception) { exception.Errors.ToList().ForEach(t => modelState.AddModelError(string.Empty, t.ErrorMessage)); }
public void HttpStatusCodeIsPopulated() { var ex = new EntityValidationException("msg"); Assert.AreEqual(HttpStatusCode.InternalServerError, ex.ResponseCode); }
public void HttpErrorMessageIsPopulated() { var ex = new EntityValidationException("msg"); Assert.AreEqual("InternalServerError", ex.HttpErrorMessage); }
private void _addValidationErrors(EntityValidationException exception) { exception.Errors.ToList().ForEach(t => ModelState.AddModelError(string.Empty, t.ErrorMessage)); }
public void IsBaseException() { var ex = new EntityValidationException("msg"); Assert.IsInstanceOfType(ex, typeof(BaseCaughtException)); }