Skip to content

fix(EventBus): Throws an exception while retaining the original stack information and does not change the exception information #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -68,11 +68,11 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async (@event) =>
if (dispatchRelation.CancelHandlers.Any())
await ExecuteEventCanceledHandlerAsync(serviceProvider, Logger, executionStrategy, dispatchRelation.CancelHandlers, @event);
else
throw new Exception(ex.Message, ex);
ex.ThrowException();
}
else
{
Logger?.LogWarning("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id);
Logger?.LogError("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id);
}
});
}
@@ -96,9 +96,9 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async @event =>
}, (@event, ex, failureLevels) =>
{
if (failureLevels != FailureLevels.Ignore)
throw new Exception(ex.Message, ex);
ex.ThrowException();

logger?.LogWarning("----- Publishing event {@Event} rollback error ignored: message id: {messageId} -----", @event, @event.Id);
logger?.LogError("----- Publishing event {@Event} rollback error ignored: message id: {messageId} -----", @event, @event.Id);
return Task.CompletedTask;
});
}
Original file line number Diff line number Diff line change
@@ -21,4 +21,13 @@ public static IServiceCollection TryAdd(this IServiceCollection services, Type s
public static bool IsGenericInterfaceAssignableFrom(this Type eventHandlerType, Type type) =>
type.IsConcrete() &&
type.GetInterfaces().Any(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == eventHandlerType);

/// <summary>
/// Keep the original stack information and throw an exception
/// </summary>
/// <param name="exception"></param>
public static void ThrowException(this Exception exception)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
1 change: 1 addition & 0 deletions src/Dispatcher/Masa.Contrib.Dispatcher.Events/_Imports.cs
Original file line number Diff line number Diff line change
@@ -15,4 +15,5 @@
global using Microsoft.Extensions.Options;
global using System.Linq.Expressions;
global using System.Reflection;
global using System.Runtime.ExceptionServices;
global using System.Text.Json.Serialization;
10 changes: 5 additions & 5 deletions test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs
Original file line number Diff line number Diff line change
@@ -58,7 +58,7 @@ public void TestTransaction()
[TestMethod]
public async Task TestUseTranscationAsync()
{
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = _options.Object.Services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
await dbContext.Database.EnsureCreatedAsync();
@@ -79,7 +79,7 @@ public async Task TestUseTranscationAsync()
[TestMethod]
public async Task TestNotUseTranscationAsync()
{
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = _options.Object.Services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
await dbContext.Database.EnsureCreatedAsync();
@@ -108,7 +108,7 @@ public async Task TestNotTransactionCommitAsync()
[TestMethod]
public async Task TestCommitAsync()
{
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = _options.Object.Services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
await dbContext.Database.EnsureCreatedAsync();
@@ -128,7 +128,7 @@ public async Task TestCommitAsync()
[TestMethod]
public async Task TestOpenRollbackAsync()
{
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = _options.Object.Services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
await dbContext.Database.EnsureCreatedAsync();
@@ -145,7 +145,7 @@ public async Task TestOpenRollbackAsync()
public async Task TestAddLoggerAndOpenRollbackAsync()
{
_options.Object.Services.AddLogging();
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = _options.Object.Services.BuildServiceProvider();
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
await dbContext.Database.EnsureCreatedAsync();
Original file line number Diff line number Diff line change
@@ -72,7 +72,7 @@ public void TestAddMultRepository()
{
_dispatcherOptions.Setup(option => option.Assemblies).Returns(_assemblies).Verifiable();
_services.AddScoped(typeof(IUnitOfWork), _ => _uoW.Object);
_services.AddMasaDbContext<CustomDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_services.AddMasaDbContext<CustomDbContext>(options => options.UseSqlite(Connection));
_dispatcherOptions.Object.UseRepository<CustomDbContext>().UseRepository<CustomDbContext>();

var serviceProvider = _services.BuildServiceProvider();
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Masa.Utils.Data.EntityFrameworkCore.Sqlite" Version="0.4.0-preview.2" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.3" />
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ public async Task InitializeAsync(Action<IServiceCollection>? action)
_dispatcherOptions.Setup(options => options.Services).Returns(() => _services);
_dispatcherOptions.Setup(options => options.Assemblies).Returns(() => _assemblies);
if (action == null)
_services.AddMasaDbContext<CustomDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
_services.AddMasaDbContext<CustomDbContext>(options => options.UseSqlite(Connection));
else
action.Invoke(_services);

@@ -364,7 +364,7 @@ public async Task TestDbTransactionAsync()
public async Task TestServiceLifeAsync()
{
var services = new ServiceCollection();
services.AddMasaDbContext<CustomDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
services.AddMasaDbContext<CustomDbContext>(options => options.UseSqlite(Connection));
var serviceProvider = services.BuildServiceProvider();

await using (var scope = serviceProvider.CreateAsyncScope())
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@
global using Masa.Contrib.Ddd.Domain.Repository.EF.Tests.Domain.Repositories;
global using Masa.Contrib.Ddd.Domain.Repository.EF.Tests.Infrastructure;
global using Masa.Utils.Data.EntityFrameworkCore;
global using Masa.Utils.Data.EntityFrameworkCore.Sqlite;
global using Microsoft.Data.Sqlite;
global using Microsoft.EntityFrameworkCore;
global using Microsoft.EntityFrameworkCore.Storage;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Masa.Contrib.Dispatcher.Events.Tests.EventHandlers;

public class RegisterUserEventHandler
{
[EventHandler]
public void RegisterUser(RegisterUserEvent registerUserEvent)
{
throw new NotSupportedException();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace Masa.Contrib.Dispatcher.Events.Tests.Events;

public record RegisterUserEvent(string Name) : Event
{
}
14 changes: 11 additions & 3 deletions test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events;

namespace Masa.Contrib.Dispatcher.Events.Tests;

[TestClass]
@@ -365,6 +363,16 @@ public void TestOrderLessThanZero()
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
{
new EventHandlerAttribute(-10);
},"The order must be greater than or equal to 0");
}, "The order must be greater than or equal to 0");
}

[TestMethod]
public async Task TestEventBusExceptionAsync()
{
var services = new ServiceCollection();
services.AddEventBus();
var registerUserEvent = new RegisterUserEvent("Jim");
var eventBus = services.BuildServiceProvider().GetRequiredService<IEventBus>();
await Assert.ThrowsExceptionAsync<NotSupportedException>(async () => await eventBus.PublishAsync(registerUserEvent));
}
}
9 changes: 1 addition & 8 deletions test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs
Original file line number Diff line number Diff line change
@@ -64,14 +64,7 @@ public async Task TestMultiHandlerBySaga(string account, string optAccount, stri
};
if (isError == 1)
{
try
{
await _eventBus.PublishAsync(@event);
}
catch (Exception ex)
{
Assert.IsTrue(ex.InnerException is NotSupportedException);
}
await Assert.ThrowsExceptionAsync<NotSupportedException>(async () => await _eventBus.PublishAsync(@event));
}
else
{
2 changes: 1 addition & 1 deletion test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
global using Masa.Contrib.Dispatcher.Events.CheckMethodsParameterType.Tests.Events;
global using Masa.Contrib.Dispatcher.Events.CheckMethodsType.Tests.Events;
global using Masa.Contrib.Dispatcher.Events.Enums;
global using Masa.Contrib.Dispatcher.Events.Options;
global using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events;
global using Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests.Events;
global using Masa.Contrib.Dispatcher.Events.Tests.Events;
global using Masa.Contrib.Dispatcher.Events.Tests.Middleware;
Original file line number Diff line number Diff line change
@@ -50,7 +50,7 @@ public async Task TestRetrieveEventLogsFailedToPublishAsync()
{
var dispatcherOptions = CreateDispatcherOptions(new ServiceCollection());
dispatcherOptions.UseEventLog<CustomDbContext>();
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option => option.DbContextOptionsBuilder.UseSqlite(Connection));
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option => option.UseSqlite(Connection));
dispatcherOptions.Services.AddScoped<IIntegrationEventLogService, IntegrationEventLogService>();
var serviceProvider = dispatcherOptions.Services.BuildServiceProvider();
await serviceProvider.GetRequiredService<CustomDbContext>().Database.EnsureCreatedAsync();
@@ -276,7 +276,7 @@ public async Task TestMarkEventAsFailed2Async()
var dispatcherOptions = CreateDispatcherOptions(new ServiceCollection());
dispatcherOptions.UseEventLog<CustomDbContext>();
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option =>
option.DbContextOptionsBuilder.UseSqlite(Connection));
option.UseSqlite(Connection));
dispatcherOptions.Services.AddScoped<IIntegrationEventLogService, IntegrationEventLogService>();
Mock<IIntegrationEventBus> integrationEventBus = new();
var types = AppDomain.CurrentDomain.GetAssemblies()