Health and Error Handling in ASP.NET π₯
The Hospital Metaphor π¨
Imagine your ASP.NET app is a busy hospital. Just like a hospital needs to:
- Check if doctors are available β
- Know when equipment breaks β οΈ
- Show patients friendly waiting rooms (not scary error rooms!)
Your app needs the same! Letβs learn how to keep your app βhealthyβ and handle problems gracefully.
1. Health Checks Basics π
What Are Health Checks?
Think of health checks like a doctor checking your heartbeat. Your app says, βIβm alive and feeling good!β or βSomethingβs wrong!β
Simple Example:
// Program.cs
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
Now visiting /health returns:
- β Healthy = Everything works!
- β οΈ Degraded = Working, but slow
- β Unhealthy = Something broke!
Real Life:
- Load balancers ask β/healthβ every few seconds
- If unhealthy, traffic goes elsewhere
- Like a nurse checking patients regularly!
2. Custom Health Checks π§
Build Your Own Checkup!
Sometimes you need special checks. Is the database alive? Is the API responding?
Example: Check if Database Works
public class DbHealthCheck : IHealthCheck
{
public Task<HealthCheckResult>
CheckHealthAsync(
HealthCheckContext context,
CancellationToken token)
{
// Try connecting to database
bool canConnect = TestDatabase();
if (canConnect)
return Task.FromResult(
HealthCheckResult.Healthy(
"Database is happy!"));
return Task.FromResult(
HealthCheckResult.Unhealthy(
"Database is sleeping!"));
}
}
Register It:
builder.Services.AddHealthChecks()
.AddCheck<DbHealthCheck>("database");
3. Health Check UI π
A Pretty Dashboard!
Why read boring text when you can see pretty colors?
// Add NuGet packages first
builder.Services
.AddHealthChecksUI()
.AddInMemoryStorage();
app.MapHealthChecksUI();
What You Get:
- π’ Green = Healthy
- π‘ Yellow = Degraded
- π΄ Red = Unhealthy
- History graphs showing uptime!
Visit /healthchecks-ui to see your dashboard!
graph TD A["Health Check UI"] --> B["π’ API: Healthy"] A --> C["π’ Database: Healthy"] A --> D["π‘ Cache: Degraded"] A --> E["π΄ Email: Unhealthy"]
4. Kubernetes Health Probes π’
Telling Kubernetes βIβm Ready!β
Kubernetes is like a ship captain. It needs to know:
- Liveness: Is the app alive? (If not, restart it!)
- Readiness: Is it ready for visitors?
- Startup: Has it finished starting?
Example Setup:
app.MapHealthChecks("/health/live",
new HealthCheckOptions
{
Predicate = _ => false // Basic alive check
});
app.MapHealthChecks("/health/ready",
new HealthCheckOptions
{
Predicate = check =>
check.Tags.Contains("ready")
});
Kubernetes YAML:
livenessProbe:
httpGet:
path: /health/live
port: 80
readinessProbe:
httpGet:
path: /health/ready
port: 80
5. Diagnostics Middleware π
Catching Problems Early
Middleware is like security guards checking everyone at the door. Diagnostics middleware watches for problems!
The Power Tool:
// Only in Development!
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
What It Catches:
- Exceptions (crashes)
- Slow requests
- Memory leaks
- Database timeouts
Think of it as having X-ray vision for your appβs problems!
6. Developer Exception Page π¨βπ»
The Super-Detailed Error Page
When something crashes, developers need details. LOTS of details!
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
What You See:
- π Full stack trace
- π Code that caused the error
- π Request details
- π¦ All query strings and headers
IMPORTANT: Never show this to real users! It reveals secrets!
graph TD A["Error Happens!"] --> B{Development?} B -->|Yes| C["Show Developer Page<br>with all details"] B -->|No| D["Show Friendly Error"]
7. Status Code Pages π’
Pretty Pages for Error Numbers
Instead of ugly β404β or β500β, show friendly pages!
Basic Setup:
app.UseStatusCodePages();
Better - Custom Messages:
app.UseStatusCodePages(async context =>
{
var code = context.HttpContext
.Response.StatusCode;
await context.HttpContext
.Response.WriteAsync(
quot;Oops! Error {code} happened!");
});
Best - Redirect to Pretty Pages:
app.UseStatusCodePagesWithReExecute(
"/error/{0}");
Now /error/404 shows your custom page!
8. Custom Error Pages π¨
Making Errors Beautiful
Users shouldnβt see scary technical stuff. Make errors friendly!
Create Error Controller:
[Route("error")]
public class ErrorController : Controller
{
[Route("{code}")]
public IActionResult Index(int code)
{
return code switch
{
404 => View("NotFound"),
500 => View("ServerError"),
_ => View("GenericError")
};
}
}
Example 404 View:
<div class="error-page">
<h1>π Page Not Found!</h1>
<p>We looked everywhere but
couldn't find that page.</p>
<a href="/">Go Home</a>
</div>
The Complete Picture πΌοΈ
graph TD A["User Request"] --> B["App"] B --> C{Error?} C -->|No| D["Happy Response! π"] C -->|Yes| E{What Kind?} E -->|404| F["Custom Not Found Page"] E -->|500| G["Custom Server Error"] E -->|Dev Mode| H["Developer Exception Page"] I["Health Checks"] --> J["/health"] J --> K["Kubernetes Probes"] J --> L["Health Check UI"]
Quick Summary π
| Feature | Purpose | When to Use |
|---|---|---|
| Health Checks | βAm I alive?β | Always |
| Custom Checks | Check specific things | Database, APIs |
| Health UI | Visual dashboard | Monitoring |
| K8s Probes | Container health | Kubernetes |
| Diagnostics | Catch problems | Development |
| Dev Exception | Detailed errors | Development |
| Status Pages | Pretty error codes | Production |
| Custom Errors | Branded error pages | Production |
You Did It! π
Now your ASP.NET app is like a well-run hospital:
- β Regular health checkups
- β Friendly staff (error pages)
- β Proper monitoring (UI dashboard)
- β Ready for the cloud (Kubernetes)
Your users will never see scary errors again, and youβll always know when something goes wrong!
Remember: Happy users = Healthy app! πͺ
