Error Handling & ProblemDetails
Sooner or later something will go wrong: a database is down, a client sends an id that does not exist, or a bug throws a NullReferenceException. A good API handles all of these consistently. The client should get a correct status code and a body it can read, and the stack trace should never leak to the public.
ASP.NET Core 9 does this with three tools that work together:
| Tool | What it does |
|---|---|
| Developer exception page | Shows a detailed HTML/text error page. On by default in the Development environment only |
UseExceptionHandler |
Middleware that catches unhandled exceptions and produces a safe response |
AddProblemDetails |
Formats error responses as ProblemDetails JSON (RFC 9457) |
IExceptionHandler |
Your own classes that turn specific exception types into specific responses |
UseStatusCodePages |
Adds a body to empty error responses such as a bare 404 |
The ProblemDetails format
Instead of making up your own error JSON, ASP.NET Core uses a standard shape. Its media type is application/problem+json:
| Field | Meaning |
|---|---|
type |
A URI that identifies the kind of problem (defaults to a link into the HTTP spec) |
title |
A short, human-readable summary |
status |
The HTTP status code, repeated in the body |
detail |
An explanation of this particular occurrence |
instance |
The request path or another URI for this occurrence |
| extensions | Any extra fields, such as traceId or errors |
Turning on the built-in handling
A typical production-ready setup is only a few lines:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(); // ProblemDetails for all errors
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler(); // catch exceptions -> 500 ProblemDetails
}
app.UseStatusCodePages(); // give empty 4xx/5xx responses a body
app.MapGet("/todos/{id:int}", (int id) =>
id == 1 ? Results.Ok(new { id, title = "Buy milk" }) : Results.NotFound());
app.MapGet("/boom", () =>
{
throw new InvalidOperationException("Database connection string is wrong");
});
app.Run();Because AddProblemDetails is registered, both UseExceptionHandler and UseStatusCodePages produce ProblemDetails JSON instead of plain text. Run it in Production mode and call the endpoints:
$ curl -i localhost:5000/todos/42
$ curl -s localhost:5000/boomHTTP/1.1 404 Not Found
Content-Type: application/problem+json
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Transfer-Encoding: chunked
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Not Found","status":404,"traceId":"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00"}
{"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-a3ce929d0e0e47364bf92f3577b34da6-b7ad6b7169203331-00"}
Notice that the exception message ("Database connection string is wrong") is not in the response. It is written to the log instead, where only you can see it. The traceId lets you find that log entry.
Tip: In the
Developmentenvironment,WebApplicationautomatically enables the developer exception page, so you see the full stack trace while coding. That is whyUseExceptionHandleris wrapped inif (!app.Environment.IsDevelopment())above.
The idea in plain C#
An exception handler is just a try/catch wrapped around the rest of the pipeline. Here is a tiny version that maps exceptions to ProblemDetails-like JSON:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
var json = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
Func<string, string> endpoint = path => path switch
{
"/todos/1" => "{\"id\":1,\"title\":\"Buy milk\"}",
"/todos/42" => throw new KeyNotFoundException("Todo 42 does not exist"),
_ => throw new InvalidOperationException("Something broke")
};
string Handle(string path)
{
try
{
return "200 " + endpoint(path);
}
catch (KeyNotFoundException ex)
{
var p = new Problem("https://tools.ietf.org/html/rfc9110#section-15.5.5", "Not Found", 404, ex.Message, path);
return "404 " + JsonSerializer.Serialize(p, json);
}
catch (Exception)
{
// never show the real message to the client
var p = new Problem("https://tools.ietf.org/html/rfc9110#section-15.6.1",
"An error occurred while processing your request.", 500, null, null);
return "500 " + JsonSerializer.Serialize(p, json);
}
}
foreach (var path in new[] { "/todos/1", "/todos/42", "/crash" })
Console.WriteLine(Handle(path));
record Problem(string Type, string Title, int Status, string? Detail, string? Instance);200 {"id":1,"title":"Buy milk"}
404 {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Not Found","status":404,"detail":"Todo 42 does not exist","instance":"/todos/42"}
500 {"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500}
Custom handlers with IExceptionHandler
Often you want certain exceptions to mean certain status codes — for example your own NotFoundException should become a 404. Implement IExceptionHandler and register it. Handlers are tried in registration order; returning true means "handled, stop here".
public sealed class NotFoundException(string message) : Exception(message);
public sealed class NotFoundHandler(IProblemDetailsService problems) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext context, Exception exception, CancellationToken ct)
{
if (exception is not NotFoundException notFound)
return false; // let the next handler try
context.Response.StatusCode = StatusCodes.Status404NotFound;
return await problems.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = context,
Exception = exception,
ProblemDetails = { Title = "Resource not found", Detail = notFound.Message }
});
}
}
// Program.cs
builder.Services.AddExceptionHandler<NotFoundHandler>();
builder.Services.AddProblemDetails();
// ...
app.UseExceptionHandler();
app.MapGet("/notes/{id:int}", (int id) =>
id < 100 ? Results.Ok(new { id }) : throw new NotFoundException(quot;Note {id} was not found."));$ curl -s localhost:5000/notes/500{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Resource not found","status":404,"detail":"Note 500 was not found.","traceId":"00-6e0f2c9b1d6a4c3c8a7e5b4d3c2b1a09-1f2e3d4c5b6a7980-00"}
Adding your own fields
AddProblemDetails accepts a callback that runs for every ProblemDetails response. It is the right place for data you want on every error, such as the request path or a support link:
builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
ctx.ProblemDetails.Instance = quot;{ctx.HttpContext.Request.Method} {ctx.HttpContext.Request.Path}";
ctx.ProblemDetails.Extensions["support"] = "https://example.com/help";
};
});Expected errors vs. exceptions
Exceptions are for unexpected situations. For normal outcomes such as "not found" or "invalid input", return a result directly — it is faster and clearer:
app.MapGet("/todos/{id:int}", (int id, TodoStore store) =>
store.Find(id) is { } todo
? Results.Ok(todo)
: Results.Problem(title: "Todo not found", detail: quot;No todo with id {id}.", statusCode: 404));Note:
Results.Problem(...)andResults.ValidationProblem(errors)(which yields a 400 with anerrorsdictionary) create ProblemDetails responses without any exception being thrown.
Test yourself
Which media type does a ProblemDetails response use?
- application/json+error
- text/problem
- application/problem+json
- application/xml
What should an IExceptionHandler.TryHandleAsync return when the exception is not one it handles?
- false, so the next handler can try
- true, to stop processing
- It should rethrow the exception
- null
Why is the exception message not included in the default 500 ProblemDetails response in Production?
- Messages are too long for JSON
- ProblemDetails has no field for it
- It could leak internal details; it is logged instead
- Kestrel strips it automatically