SkillPilotAI

Error handling and health checks

Error handling decides what the client gets when something throws, and health checks tell a load balancer or Kubernetes whether the app is alive and ready. In ASP.NET Core the standard answer is ProblemDetails with UseExceptionHandler, IExceptionHandler for domain errors, and separate liveness and readiness endpoints.

44.1 Why is it used?

  • Without a handler, an unhandled exception gives the client an empty 500 and a wrong URL an empty 404: the client has no idea what went wrong.
  • One central handler sends every error in one standard format (ProblemDetails, RFC 9457).
  • Domain errors (order not found) should map to the right status (404, 409), not 500.
  • Orchestrators need health endpoints to restart dead pods and route traffic only to ready ones.

44.2 The bug: empty 500

C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<OrderStore>(); var app = builder.Build(); app.MapGet("/api/orders/{id:int}",    (int id, OrderStore store) => store.Get(id)); app.Run();
Output
$ curl -i localhost:5044/api/orders/7HTTP/1.1 500 Internal Server ErrorContent-Length: 0Server: Kestrel $ curl -i localhost:5044/api/order/1HTTP/1.1 404 Not FoundContent-Length: 0Server: Kestrel

The same app in the Development environment shows the developer exception page (turned on automatically in Development):

Output
# ASPNETCORE_ENVIRONMENT=Development$ curl -i localhost:5044/api/orders/7HTTP/1.1 500 Internal Server ErrorContent-Type: text/plain; charset=utf-8OrderNotFoundException: Order 7 not found   at OrderStore.Get(Int32 id) in   D:\SkillUp\tmp-C44\Shop\Orders.cs:line 14   at Program.<>c.<<Main>$>b__0_0(...)
  • The exception is thrown inside the endpoint and no middleware catches it, so Kestrel sends an empty 500.
  • In Development the developer exception page catches it but leaks the stack trace and file paths, which must never reach production clients.
Why an empty 500?
  1. 1.Exception thrown: order 7 not found

  2. 2.No handler in the pipeline

  3. 3.Production: Kestrel sends an empty 500

  4. 4.Development: developer page leaks the stack trace

Needed: a central handler + a standard format

44.3 Fix: ProblemDetails + UseExceptionHandler

C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<OrderStore>();builder.Services.AddProblemDetails(); var app = builder.Build(); app.UseExceptionHandler();app.UseStatusCodePages(); app.MapGet("/api/orders/{id:int}",    (int id, OrderStore store) => store.Get(id)); app.Run();
Output
$ curl -i localhost:5044/api/orders/7HTTP/1.1 500 Internal Server ErrorContent-Type: application/problem+json{  "type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",  "title": "An error occurred while processing your request.",  "status": 500,  "traceId": "00-a55d2361...-00"} $ curl -i localhost:5044/api/order/1HTTP/1.1 404 Not FoundContent-Type: application/problem+json{  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",  "title": "Not Found",  "status": 404,  "traceId": "00-f5339570...-00"}
  • AddProblemDetails registers the service that writes errors in the ProblemDetails format.
  • UseExceptionHandler catches every unhandled exception.
  • UseStatusCodePages fills empty error responses (like the 404 for a typo URL) with the same format.
  • Content-Type is application/problem+json; the body has type, title, status and traceId.

44.4 IExceptionHandler: 404, not 500

C#
public class OrderErrorHandler : IExceptionHandler{    public async ValueTask<bool> TryHandleAsync(        HttpContext http, Exception ex,        CancellationToken ct)    {        if (ex is not OrderNotFoundException)            return false;        await Results.Problem(            title: "Order not found",            detail: ex.Message,            statusCode: 404).ExecuteAsync(http);        return true;    }}
C#
builder.Services.AddExceptionHandler<OrderErrorHandler>();
Output
$ curl -i localhost:5044/api/orders/7HTTP/1.1 404 Not FoundContent-Type: application/problem+json{  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",  "title": "Order not found",  "status": 404,  "detail": "Order 7 not found",  "traceId": "00-0bde4121...-00"}
  • A missing order is not a server mistake, so it should be a 404.
  • TryHandleAsync receives every exception; return false = "not mine", let the next handler try.
  • Results.Problem(title, detail, statusCode: 404).ExecuteAsync(http) writes the response, then return true.
  • Register with AddExceptionHandler<T>(); several handlers run in registration order.
The full exception flow
  1. 1.Endpoint throws; UseExceptionHandler catches it

  2. 2.Registered IExceptionHandlers run in order

  3. 3.First one that returns true writes the response

  4. 4.All false: default handler sends a generic 500 ProblemDetails

  5. 5.Client gets title, status, traceId; stack trace goes to server logs

Standard format for the client, details only on the server

44.5 Checkpoint: what does a TimeoutException give?

C#
builder.Services.AddProblemDetails();builder.Services    .AddExceptionHandler<OrderErrorHandler>(); var app = builder.Build(); app.UseExceptionHandler();app.UseStatusCodePages(); app.MapPost("/api/payments", () =>{    throw new TimeoutException(        "UPI gateway timeout at 10.0.4.12");});
Output
$ curl -i -X POST localhost:5044/api/paymentsHTTP/1.1 500 Internal Server ErrorContent-Type: application/problem+json{  "title": "An error occurred while processing your request.",  "status": 500,  "traceId": "00-66b8b0fe...-00", ...} # server consolefail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]      An unhandled exception has occurred while executing the request.      System.TimeoutException: UPI gateway timeout at 10.0.4.12
  • OrderErrorHandler returns false for TimeoutException, so the default handler sends a generic 500.
  • The message (with the internal gateway IP 10.0.4.12) is not put in the response.
  • The full exception is logged on the server; the client's traceId lets you find the exact request in the logs.

44.6 Health checks: a custom check

C#
public async Task<HealthCheckResult>    CheckHealthAsync(HealthCheckContext context,        CancellationToken ct = default){    try    {        using var tcp = new TcpClient();        await tcp.ConnectAsync("db", 5432, ct);        return HealthCheckResult.Healthy();    }    catch (SocketException)    {        return HealthCheckResult.Unhealthy();    }}
  • IHealthCheck.CheckHealthAsync tries a TCP connection to the database server (db:5432).
  • Connected: HealthCheckResult.Healthy(); SocketException: Unhealthy().

44.7 Liveness vs readiness

C#
builder.Services.AddHealthChecks()    .AddCheck<DatabaseHealthCheck>(        "database", tags: ["ready"]); var app = builder.Build(); app.MapHealthChecks("/health/live", new(){    Predicate = _ => false});app.MapHealthChecks("/health/ready", new(){    Predicate = c => c.Tags.Contains("ready")});
Output
$ curl -i localhost:5044/health/liveHTTP/1.1 200 OKContent-Type: text/plainCache-Control: no-store, no-cacheHealthy $ curl -i localhost:5044/health/readyHTTP/1.1 503 Service UnavailableContent-Type: text/plainCache-Control: no-store, no-cacheUnhealthy
  • The check is registered with the "ready" tag.
  • /health/live has Predicate = _ => false: runs no checks, only proves the process is alive (200 Healthy).
  • /health/ready runs only checks tagged ready; no local database, so 503 Unhealthy.
PointLiveness (/health/live)Readiness (/health/ready)
QuestionIs the process alive?Can it serve traffic now?
ChecksNone (process only)Dependencies: database, cache, APIs
On failureOrchestrator restarts the podPod is taken out of traffic, not restarted
Database here?No: DB down = restart loopYes
How Kubernetes uses the two probes
  1. 1.Pod starts

  2. 2.Readiness probe: /health/ready

  3. 3.DB unreachable -> 503 -> no traffic sent to this pod

  4. 4.Liveness probe: /health/live -> 200, so no restart

  5. 5.DB back -> ready 200 -> traffic resumes

Restarting never fixes a database

44.8 Common mistakes

  • UseDeveloperExceptionPage in every environment: the exception name and server file path reach the client, free information for an attacker.
  • Putting the database in liveness: DB down makes every pod restart in a loop.
  • Sending the message of an unexpected exception to the client (it can contain internal IPs).
  • In .NET 10 exceptions handled by an IExceptionHandler are not logged by default: log them yourself with ILogger when you need to.
C#
var app = builder.Build(); app.UseDeveloperExceptionPage(); // Production: curl /api/orders/7// 500, text/plain// OrderNotFoundException: Order 7 not found//   at OrderStore.Get(Int32 id) in//   D:\SkillUp\...\Orders.cs:line 14

Right: UseExceptionHandler + UseStatusCodePages; the client gets 404 application/problem+json and the stack trace stays in server logs.

44.9 Rules for error handling

  1. AddProblemDetails + UseExceptionHandler + UseStatusCodePages so every error has one format.
  2. Map domain exceptions to the correct status with IExceptionHandler.
  3. Never send a stack trace or unexpected exception message to the client.
  4. Handled exception? Log it yourself.
  5. Separate liveness and readiness endpoints.

44.10 Interview tips

  • AddProblemDetails, UseExceptionHandler and UseStatusCodePages make every error go out in RFC 9457 ProblemDetails format.
  • Domain exceptions are mapped by IExceptionHandler to 404 or 409; unexpected errors get a generic 500 with a traceId.
  • Details stay in server logs; the traceId connects a client error to the log entry.
  • Liveness checks only the process; readiness checks dependencies like the database.