Skip to content

fix(DbContextHealthCheck): propagate OperationCanceledExceptions instead of reporting unhealthy #61883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,24 @@ namespace Microsoft.Extensions.Diagnostics.HealthChecks;

internal sealed class DbContextHealthCheck<TContext> : IHealthCheck where TContext : DbContext
{
private static readonly Func<TContext, CancellationToken, Task<bool>> DefaultTestQuery = (dbContext, cancellationToken) =>
private static readonly Func<TContext, CancellationToken, Task<bool>> DefaultTestQuery = async (dbContext, cancellationToken) =>
{
return dbContext.Database.CanConnectAsync(cancellationToken);
try
{
return await dbContext.Database.CanConnectAsync(cancellationToken);
}
catch (Exception exception)
{
// every exception returned by `CanConnectAsync` indicates cancellation, but we have to wrap every
// non-OperationCanceledException to make the check health message properly propagate, independent of the
// test query being used
if (exception is not OperationCanceledException)
{
throw new OperationCanceledException(null, exception, cancellationToken);
}

throw;
}
};

private readonly TContext _dbContext;
Expand Down Expand Up @@ -41,7 +56,7 @@ public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context

return new HealthCheckResult(context.Registration.FailureStatus);
}
catch (Exception exception)
catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
return HealthCheckResult.Unhealthy(exception.Message, exception);
}
Expand Down
Loading