Skip to content

Commit b2cb8c9

Browse files
committed
Fix ignored exceptions in MqttHostedServer startup
1 parent 63d8518 commit b2cb8c9

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

Source/MQTTnet.AspnetCore/MqttHostedServer.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
using System.Threading;
88
using System.Threading.Tasks;
99
using Microsoft.Extensions.Hosting;
10+
using Microsoft.Extensions.Logging;
11+
using Microsoft.Extensions.Logging.Abstractions;
1012
using MQTTnet.Diagnostics.Logger;
1113
using MQTTnet.Server;
1214

@@ -16,16 +18,20 @@ public sealed class MqttHostedServer : MqttServer, IHostedService
1618
{
1719
readonly IHostApplicationLifetime _hostApplicationLifetime;
1820
readonly MqttServerFactory _mqttFactory;
21+
readonly ILogger _appLogger;
1922

2023
public MqttHostedServer(
2124
IHostApplicationLifetime hostApplicationLifetime,
2225
MqttServerFactory mqttFactory,
2326
MqttServerOptions options,
2427
IEnumerable<IMqttServerAdapter> adapters,
25-
IMqttNetLogger logger) : base(options, adapters, logger)
28+
IMqttNetLogger logger,
29+
ILogger<MqttHostedServer> appLogger = null
30+
) : base(options, adapters, logger)
2631
{
2732
_mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
2833
_hostApplicationLifetime = hostApplicationLifetime;
34+
_appLogger = appLogger ?? NullLogger<MqttHostedServer>.Instance;
2935
}
3036

3137
public async Task StartAsync(CancellationToken cancellationToken)
@@ -43,6 +49,19 @@ public Task StopAsync(CancellationToken cancellationToken)
4349

4450
void OnStarted()
4551
{
46-
_ = StartAsync();
52+
async Task DoStart()
53+
{
54+
try
55+
{
56+
await StartAsync();
57+
}
58+
catch (Exception e)
59+
{
60+
_appLogger.LogError(e, "Stopping application: failed to start MqttServer: {Error}", e.Message);
61+
_hostApplicationLifetime.StopApplication();
62+
throw;
63+
}
64+
}
65+
_ = DoStart();
4766
}
4867
}

0 commit comments

Comments
 (0)