@@ -8,9 +8,24 @@ namespace Microsoft.Extensions.Diagnostics.HealthChecks;
88
99internal sealed class DbContextHealthCheck < TContext > : IHealthCheck where TContext : DbContext
1010{
11- private static readonly Func < TContext , CancellationToken , Task < bool > > DefaultTestQuery = ( dbContext , cancellationToken ) =>
11+ private static readonly Func < TContext , CancellationToken , Task < bool > > DefaultTestQuery = async ( dbContext , cancellationToken ) =>
1212 {
13- return dbContext . Database . CanConnectAsync ( cancellationToken ) ;
13+ try
14+ {
15+ return await dbContext . Database . CanConnectAsync ( cancellationToken ) ;
16+ }
17+ catch ( Exception exception )
18+ {
19+ // every exception returned by `CanConnectAsync` indicates cancellation, but we have to wrap every
20+ // non-OperationCanceledException to make the check health message properly propagate, independent of the
21+ // test query being used
22+ if ( exception is not OperationCanceledException )
23+ {
24+ throw new OperationCanceledException ( null , exception , cancellationToken ) ;
25+ }
26+
27+ throw ;
28+ }
1429 } ;
1530
1631 private readonly TContext _dbContext ;
@@ -41,7 +56,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
4156
4257 return new HealthCheckResult ( context . Registration . FailureStatus ) ;
4358 }
44- catch ( Exception exception )
59+ catch ( Exception exception ) when ( exception is not OperationCanceledException || ! cancellationToken . IsCancellationRequested )
4560 {
4661 return HealthCheckResult . Unhealthy ( exception . Message , exception ) ;
4762 }
0 commit comments