5.1 Global Exception Handling
// IExceptionHandler (built-in, .NET 8+) — RFC 7807 Problem Details
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) => _logger = logger;
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(exception, "Unhandled exception for {Path}", httpContext.Request.Path);
var (statusCode, title) = exception switch
{
NotFoundException => (StatusCodes.Status404NotFound, "Resource not found"),
ValidationException => (StatusCodes.Status400BadRequest, "Validation failed"),
_ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred")
};
httpContext.Response.StatusCode = statusCode;
await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = statusCode,
Title = title,
Detail = exception.Message,
Instance = httpContext.Request.Path
}, cancellationToken);
return true; // Exception handled
}
}
// Registration
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
app.UseExceptionHandler(); // No path needed — delegates to registered IExceptionHandler
Standardizing on RFC 7807 Problem Details gives every error response a consistent shape (type, title, status, detail, instance) that API consumers can parse uniformly, instead of every controller inventing its own error JSON.
5.2 Middleware Pipeline for APIs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApi();
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
// Minimal API alternative (no controllers)
app.MapGet("/orders/{id:int}", async (int id, IOrderRepository repo) =>
{
var order = await repo.FindAsync(id);
return order is not null ? Results.Ok(order) : Results.NotFound();
})
.WithName("GetOrder")
.Produces<Order>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);
5.3 OpenTelemetry Integration
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("order-service"))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddEntityFrameworkCoreInstrumentation()
.AddOtlpExporter(otlp => otlp.Endpoint = new Uri("http://otel-collector:4317")))
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddRuntimeInstrumentation()
.AddOtlpExporter());
// Custom spans for business-level tracing
public class OrderService
{
private static readonly ActivitySource ActivitySource = new("OrderService");
public async Task<Order> ProcessOrderAsync(OrderRequest request)
{
using var activity = ActivitySource.StartActivity("ProcessOrder");
activity?.SetTag("order.customerId", request.CustomerId);
// ... business logic ...
activity?.SetTag("order.total", order.Total);
return order;
}
}
This gives distributed traces spanning ASP.NET Core request handling, outbound HttpClient calls, and EF Core queries — correlated via a single trace ID exported to any OTLP-compatible backend (Jaeger, Tempo, Application Insights, Honeycomb).
Interview Q&A — Section 5
Q1: How do you design global exception handling in an ASP.NET Core Web API?
A: I intercept the pipeline globally with
IExceptionHandler(built-in since .NET 8) rather than scattering try/catch in every controller. It maps known exception types to appropriate HTTP status codes and formats every error as an RFC 7807 Problem Details response, so API consumers get a consistent error shape regardless of which controller or endpoint threw. It also centralizes logging — every unhandled exception is logged exactly once, with request path/correlation ID attached.
Q2: Why does middleware ordering matter specifically for authentication and authorization?
A:
UseAuthentication()populatesHttpContext.Userfrom the request’s credentials (JWT, cookie, etc.);UseAuthorization()then checks that populated principal against policy/role requirements. If authorization runs first, it evaluates against an anonymous/unauthenticated user and every protected endpoint incorrectly returns 401/403 regardless of valid credentials. Exception-handling middleware must also be registered before routing/auth so it can catch exceptions thrown anywhere downstream in the pipeline.
Q3: How do you get end-to-end distributed tracing across a .NET microservice and its dependencies?
A: I wire up OpenTelemetry with
AddAspNetCoreInstrumentation()for inbound HTTP requests,AddHttpClientInstrumentation()for outbound calls, andAddEntityFrameworkCoreInstrumentation()for DB queries, all exported via OTLP to a collector feeding Jaeger/Tempo or a vendor APM. Each inbound request gets a trace ID that automatically propagates through outbound HTTP headers to downstream services, so a single request across five microservices shows up as one connected trace. I supplement automatic instrumentation with customActivityspans around key business operations so traces reflect domain logic, not just HTTP/DB boundaries.