Health and Error Handling

Back

Loading concept...

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&lt;br&gt;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! πŸ’ͺ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.