AddDbContextCheck - adding messages indicating reason for failure #56359
-
Hello! We've noticed AddDbContextCheck does not report the reason that the check failed. This healthcheck is tied to our Kubernetes readiness check, so the app becomes inaccessible from the reverse proxy when the check fails, and it therefore becomes difficult to make the app try and execute a query to get an error message. So if we have an issue with our database, which could be auth-related, network-related, etc. all we have to go off of is this log line repeated a lot:
It can be particularly hard to debug the issue if it's related to the specific credentials that the app is using (especially if using Kerberos / trusted connections) or the network route between the app and the DB server. Anyway, I noticed that I can fix this by passing in a services.AddHealthChecks().AddDbContextCheck<MyContext>(
"MyContext",
customTestQuery: static async (context, cancellationToken) =>
{
await context.Database.ExecuteSqlRawAsync("SELECT 1");
return true;
}
); However the docs advise against throwing exceptions in the check:
I would like to ask why the above approach is not recommended, and whether there is an alternative way to return some more detailed information about why the check has failed. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The purpose of services.AddHealthChecks().AddDbContextCheck<MyContext>(
"MyContext",
customTestQuery: async (context, cancellationToken) =>
{
try
{
await context.Database.ExecuteSqlRawAsync("SELECT 1", cancellationToken);
return true;
}
catch (Exception ex)
{
// Log the exception details ex.Message
// Return false to indicate the health check has failed
return false;
}
},
); |
Beta Was this translation helpful? Give feedback.
The purpose of
AddDbContextCheck
is to determine if the application can connect to the database. If the health check relies on exceptions, there’s a risk that transient issues could cause the check to report unhealthy, even if the issue is momentary and could be resolved with a retry.Maybe you can implement a custom health check that does a more detailed check and captures any exceptions thrown. You can then log the exception details while ensuring the health check remains performant by returning a failed result without rethrowing the exception. For example: