Skip to content

Commit 7982641

Browse files
Distributed Background Jobs: Catch exceptions in job loop to improve application resilience (#21099)
* Set exit code when exception is thrown * Catch any error instead so we don't stop the application * Handle exception when ensuring jobs
1 parent 85806fd commit 7982641

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

src/Umbraco.Infrastructure/BackgroundJobs/DistributedBackgroundJobHostedService.cs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,38 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
4747
await Task.Delay(_distributedJobSettings.Delay, stoppingToken);
4848
}
4949

50-
// Update all jobs, periods might have changed when restarting.
51-
await _distributedJobService.EnsureJobsAsync();
50+
try
51+
{
52+
// Update all jobs, periods might have changed when restarting.
53+
await _distributedJobService.EnsureJobsAsync();
54+
}
55+
catch (Exception exception)
56+
{
57+
// We swallow exception here, don't want the app to crash if something goes wrong
58+
_logger.LogError(exception, "An exception occurred while attempting to ensure distributed background jobs on startup.");
59+
}
60+
5261

5362
using PeriodicTimer timer = new(_distributedJobSettings.Period);
5463

5564
try
5665
{
5766
while (await timer.WaitForNextTickAsync(stoppingToken))
5867
{
59-
await RunRunnableJob();
68+
try
69+
{
70+
await RunRunnableJob();
71+
}
72+
catch (Exception exception)
73+
{
74+
if (exception is OperationCanceledException)
75+
{
76+
// If the operation was canceled, just re-throw to stop the service
77+
throw;
78+
}
79+
80+
_logger.LogError(exception, "An exception occurred while attempting to run a distributed background job.");
81+
}
6082
}
6183
}
6284
catch (OperationCanceledException)

0 commit comments

Comments
 (0)