Skip to content

Commit ff24f8c

Browse files
authored
fix(EventBus): Throws an exception while retaining the original stack information and does not change the exception information (#25)
* fix(EventBus): Throws an exception while retaining the original stack information and does not change the exception information * test(EventBus): Custom exception unit test to detect unchanged stack information * test: Adapt to Utils.EntityFramework 0.4.0-preview.2
1 parent 35dd929 commit ff24f8c

File tree

14 files changed

+55
-26
lines changed

14 files changed

+55
-26
lines changed

src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/Dispatch/DispatcherBase.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,11 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async (@event) =>
6868
if (dispatchRelation.CancelHandlers.Any())
6969
await ExecuteEventCanceledHandlerAsync(serviceProvider, Logger, executionStrategy, dispatchRelation.CancelHandlers, @event);
7070
else
71-
throw new Exception(ex.Message, ex);
71+
ex.ThrowException();
7272
}
7373
else
7474
{
75-
Logger?.LogWarning("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id);
75+
Logger?.LogError("----- Publishing event {@Event} error rollback is ignored: message id: {messageId} -----", @event, @event.Id);
7676
}
7777
});
7878
}
@@ -96,9 +96,9 @@ await executionStrategy.ExecuteAsync(strategyOptions, @event, async @event =>
9696
}, (@event, ex, failureLevels) =>
9797
{
9898
if (failureLevels != FailureLevels.Ignore)
99-
throw new Exception(ex.Message, ex);
99+
ex.ThrowException();
100100

101-
logger?.LogWarning("----- Publishing event {@Event} rollback error ignored: message id: {messageId} -----", @event, @event.Id);
101+
logger?.LogError("----- Publishing event {@Event} rollback error ignored: message id: {messageId} -----", @event, @event.Id);
102102
return Task.CompletedTask;
103103
});
104104
}

src/Dispatcher/Masa.Contrib.Dispatcher.Events/Internal/DispatcherExtensions.cs

+9
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,13 @@ public static IServiceCollection TryAdd(this IServiceCollection services, Type s
2121
public static bool IsGenericInterfaceAssignableFrom(this Type eventHandlerType, Type type) =>
2222
type.IsConcrete() &&
2323
type.GetInterfaces().Any(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == eventHandlerType);
24+
25+
/// <summary>
26+
/// Keep the original stack information and throw an exception
27+
/// </summary>
28+
/// <param name="exception"></param>
29+
public static void ThrowException(this Exception exception)
30+
{
31+
ExceptionDispatchInfo.Capture(exception).Throw();
32+
}
2433
}

src/Dispatcher/Masa.Contrib.Dispatcher.Events/_Imports.cs

+1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@
1515
global using Microsoft.Extensions.Options;
1616
global using System.Linq.Expressions;
1717
global using System.Reflection;
18+
global using System.Runtime.ExceptionServices;
1819
global using System.Text.Json.Serialization;

test/Masa.Contrib.Data.UoW.EF.Tests/TestUnitOfWork.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public void TestTransaction()
5858
[TestMethod]
5959
public async Task TestUseTranscationAsync()
6060
{
61-
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
61+
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
6262
var serviceProvider = _options.Object.Services.BuildServiceProvider();
6363
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
6464
await dbContext.Database.EnsureCreatedAsync();
@@ -79,7 +79,7 @@ public async Task TestUseTranscationAsync()
7979
[TestMethod]
8080
public async Task TestNotUseTranscationAsync()
8181
{
82-
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
82+
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
8383
var serviceProvider = _options.Object.Services.BuildServiceProvider();
8484
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
8585
await dbContext.Database.EnsureCreatedAsync();
@@ -108,7 +108,7 @@ public async Task TestNotTransactionCommitAsync()
108108
[TestMethod]
109109
public async Task TestCommitAsync()
110110
{
111-
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
111+
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
112112
var serviceProvider = _options.Object.Services.BuildServiceProvider();
113113
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
114114
await dbContext.Database.EnsureCreatedAsync();
@@ -128,7 +128,7 @@ public async Task TestCommitAsync()
128128
[TestMethod]
129129
public async Task TestOpenRollbackAsync()
130130
{
131-
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
131+
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
132132
var serviceProvider = _options.Object.Services.BuildServiceProvider();
133133
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
134134
await dbContext.Database.EnsureCreatedAsync();
@@ -145,7 +145,7 @@ public async Task TestOpenRollbackAsync()
145145
public async Task TestAddLoggerAndOpenRollbackAsync()
146146
{
147147
_options.Object.Services.AddLogging();
148-
_options.Object.UseUoW<CustomerDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
148+
_options.Object.UseUoW<CustomerDbContext>(options => options.UseSqlite(Connection));
149149
var serviceProvider = _options.Object.Services.BuildServiceProvider();
150150
var dbContext = serviceProvider.GetRequiredService<CustomerDbContext>();
151151
await dbContext.Database.EnsureCreatedAsync();

test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/BaseRepositoryTest.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public void TestAddMultRepository()
7272
{
7373
_dispatcherOptions.Setup(option => option.Assemblies).Returns(_assemblies).Verifiable();
7474
_services.AddScoped(typeof(IUnitOfWork), _ => _uoW.Object);
75-
_services.AddMasaDbContext<CustomDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
75+
_services.AddMasaDbContext<CustomDbContext>(options => options.UseSqlite(Connection));
7676
_dispatcherOptions.Object.UseRepository<CustomDbContext>().UseRepository<CustomDbContext>();
7777

7878
var serviceProvider = _services.BuildServiceProvider();

test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Masa.Contrib.Ddd.Domain.Repository.EF.Tests.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<PrivateAssets>all</PrivateAssets>
1313
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
1414
</PackageReference>
15+
<PackageReference Include="Masa.Utils.Data.EntityFrameworkCore.Sqlite" Version="0.4.0-preview.2" />
1516
<PackageReference Include="Moq" Version="4.16.1" />
1617
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
1718
<PackageReference Include="MSTest.TestAdapter" Version="2.2.3" />

test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/RepositoryTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public async Task InitializeAsync(Action<IServiceCollection>? action)
2626
_dispatcherOptions.Setup(options => options.Services).Returns(() => _services);
2727
_dispatcherOptions.Setup(options => options.Assemblies).Returns(() => _assemblies);
2828
if (action == null)
29-
_services.AddMasaDbContext<CustomDbContext>(options => options.DbContextOptionsBuilder.UseSqlite(Connection));
29+
_services.AddMasaDbContext<CustomDbContext>(options => options.UseSqlite(Connection));
3030
else
3131
action.Invoke(_services);
3232

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

370370
await using (var scope = serviceProvider.CreateAsyncScope())

test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/_Imports.cs

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
global using Masa.Contrib.Ddd.Domain.Repository.EF.Tests.Domain.Repositories;
1111
global using Masa.Contrib.Ddd.Domain.Repository.EF.Tests.Infrastructure;
1212
global using Masa.Utils.Data.EntityFrameworkCore;
13+
global using Masa.Utils.Data.EntityFrameworkCore.Sqlite;
1314
global using Microsoft.Data.Sqlite;
1415
global using Microsoft.EntityFrameworkCore;
1516
global using Microsoft.EntityFrameworkCore.Storage;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace Masa.Contrib.Dispatcher.Events.Tests.EventHandlers;
2+
3+
public class RegisterUserEventHandler
4+
{
5+
[EventHandler]
6+
public void RegisterUser(RegisterUserEvent registerUserEvent)
7+
{
8+
throw new NotSupportedException();
9+
}
10+
}
11+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
namespace Masa.Contrib.Dispatcher.Events.Tests.Events;
2+
3+
public record RegisterUserEvent(string Name) : Event
4+
{
5+
}

test/Masa.Contrib.Dispatcher.Events.Tests/FeaturesTest.cs

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events;
2-
31
namespace Masa.Contrib.Dispatcher.Events.Tests;
42

53
[TestClass]
@@ -365,6 +363,16 @@ public void TestOrderLessThanZero()
365363
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
366364
{
367365
new EventHandlerAttribute(-10);
368-
},"The order must be greater than or equal to 0");
366+
}, "The order must be greater than or equal to 0");
367+
}
368+
369+
[TestMethod]
370+
public async Task TestEventBusExceptionAsync()
371+
{
372+
var services = new ServiceCollection();
373+
services.AddEventBus();
374+
var registerUserEvent = new RegisterUserEvent("Jim");
375+
var eventBus = services.BuildServiceProvider().GetRequiredService<IEventBus>();
376+
await Assert.ThrowsExceptionAsync<NotSupportedException>(async () => await eventBus.PublishAsync(registerUserEvent));
369377
}
370378
}

test/Masa.Contrib.Dispatcher.Events.Tests/SagaTest.cs

+1-8
Original file line numberDiff line numberDiff line change
@@ -64,14 +64,7 @@ public async Task TestMultiHandlerBySaga(string account, string optAccount, stri
6464
};
6565
if (isError == 1)
6666
{
67-
try
68-
{
69-
await _eventBus.PublishAsync(@event);
70-
}
71-
catch (Exception ex)
72-
{
73-
Assert.IsTrue(ex.InnerException is NotSupportedException);
74-
}
67+
await Assert.ThrowsExceptionAsync<NotSupportedException>(async () => await _eventBus.PublishAsync(@event));
7568
}
7669
else
7770
{

test/Masa.Contrib.Dispatcher.Events.Tests/_Imports.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
global using Masa.Contrib.Dispatcher.Events.CheckMethodsParameterType.Tests.Events;
77
global using Masa.Contrib.Dispatcher.Events.CheckMethodsType.Tests.Events;
88
global using Masa.Contrib.Dispatcher.Events.Enums;
9-
global using Masa.Contrib.Dispatcher.Events.Options;
9+
global using Masa.Contrib.Dispatcher.Events.HandlerOrder.Tests.Events;
1010
global using Masa.Contrib.Dispatcher.Events.OrderEqualBySaga.Tests.Events;
1111
global using Masa.Contrib.Dispatcher.Events.Tests.Events;
1212
global using Masa.Contrib.Dispatcher.Events.Tests.Middleware;

test/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EF.Tests/IntegrationEventLogServiceTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public async Task TestRetrieveEventLogsFailedToPublishAsync()
5050
{
5151
var dispatcherOptions = CreateDispatcherOptions(new ServiceCollection());
5252
dispatcherOptions.UseEventLog<CustomDbContext>();
53-
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option => option.DbContextOptionsBuilder.UseSqlite(Connection));
53+
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option => option.UseSqlite(Connection));
5454
dispatcherOptions.Services.AddScoped<IIntegrationEventLogService, IntegrationEventLogService>();
5555
var serviceProvider = dispatcherOptions.Services.BuildServiceProvider();
5656
await serviceProvider.GetRequiredService<CustomDbContext>().Database.EnsureCreatedAsync();
@@ -276,7 +276,7 @@ public async Task TestMarkEventAsFailed2Async()
276276
var dispatcherOptions = CreateDispatcherOptions(new ServiceCollection());
277277
dispatcherOptions.UseEventLog<CustomDbContext>();
278278
dispatcherOptions.Services.AddMasaDbContext<CustomDbContext>(option =>
279-
option.DbContextOptionsBuilder.UseSqlite(Connection));
279+
option.UseSqlite(Connection));
280280
dispatcherOptions.Services.AddScoped<IIntegrationEventLogService, IntegrationEventLogService>();
281281
Mock<IIntegrationEventBus> integrationEventBus = new();
282282
var types = AppDomain.CurrentDomain.GetAssemblies()

0 commit comments

Comments
 (0)