@@ -8,9 +8,24 @@ namespace Microsoft.Extensions.Diagnostics.HealthChecks;
8
8
9
9
internal sealed class DbContextHealthCheck < TContext > : IHealthCheck where TContext : DbContext
10
10
{
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 ) =>
12
12
{
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
+ }
14
29
} ;
15
30
16
31
private readonly TContext _dbContext ;
@@ -41,7 +56,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context
41
56
42
57
return new HealthCheckResult ( context . Registration . FailureStatus ) ;
43
58
}
44
- catch ( Exception exception )
59
+ catch ( Exception exception ) when ( exception is not OperationCanceledException || ! cancellationToken . IsCancellationRequested )
45
60
{
46
61
return HealthCheckResult . Unhealthy ( exception . Message , exception ) ;
47
62
}
0 commit comments