Error Handling, ProblemDetails and Logging
Why Central Error Handling?
Without it a crash returns an ugly page or leaks a stack trace. With it every error becomes a clean, consistent JSON answer and is written to the log.
ProblemDetails: The Standard Error Format
json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "Not Found",
"status": 404,
"detail": "Book 99 was not found.",
"traceId": "00-6c1b..."
}
csharp
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler(); // unhandled exceptions become 500 ProblemDetails
app.UseStatusCodePages(); // plain 404/401 etc. also get a body
Return Problems Yourself
csharp
app.MapGet("/books/{id:int}", (int id) =>
id == 99
? Results.Problem(title: "Book not found", detail: $"Book {id} does not exist.", statusCode: 404)
: Results.Ok());
A Global Exception Handler
csharp
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public class AppExceptionHandler(ILogger<AppExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext context, Exception exception, CancellationToken cancellationToken)
{
var (status, title) = exception switch
{
KeyNotFoundException => (StatusCodes.Status404NotFound, "Resource not found"),
InvalidOperationException => (StatusCodes.Status409Conflict, "Operation not allowed"),
_ => (StatusCodes.Status500InternalServerError, "Server error")
};
if (status == 500)
logger.LogError(exception, "Unhandled exception for {Path}", context.Request.Path);
context.Response.StatusCode = status;
await context.Response.WriteAsJsonAsync(
new ProblemDetails { Status = status, Title = title }, cancellationToken);
return true; // handled: stop other handlers
}
}
// Program.cs
builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddProblemDetails();
app.UseExceptionHandler();
Do not leak details: Never send exception messages or stack traces to clients in production. Log them on the server and return a generic message plus a trace id.
Logging with ILogger
csharp
public class OrderService(ILogger<OrderService> logger)
{
public void Place(int orderId, decimal total)
{
logger.LogInformation("Order {OrderId} placed with total {Total}", orderId, total);
if (total > 10_000)
logger.LogWarning("Large order {OrderId}: {Total}", orderId, total);
}
}
Structured logging: Write
{OrderId} placeholders instead of building a string with $"...". The logging system keeps the values as separate fields, so you can search for OrderId = 5 in tools like Seq, Elastic or Application Insights.
| Level | Use for |
|---|---|
Trace, Debug | Detailed information for development |
Information | Normal events: request done, order placed |
Warning | Something unusual that still works |
Error | A failure of one operation |
Critical | The application is in serious trouble |
Configure Levels
json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
}
}
The last line prints the SQL that EF Core runs.
Serilog in Two Lines
bash
dotnet add package Serilog.AspNetCore
csharp
builder.Host.UseSerilog((context, config) => config
.ReadFrom.Configuration(context.Configuration)
.WriteTo.Console()
.WriteTo.File("logs/app-.log", rollingInterval: RollingInterval.Day));
What to log: Log decisions and failures with identifiers (order id, user id), never passwords, tokens or full card numbers.
Conclusion
Use ProblemDetails for consistent errors, one global exception handler, structured logging with placeholders and the right log level for each message.
Quick Summary: UseExceptionHandler + ProblemDetails + IExceptionHandler. Log with placeholders, not string concatenation.

