Yes. Let exceptions bubble up and handle them in one place with middleware. That keeps controllers short and makes every error response look the same.
In .NET 8 the simplest way is IExceptionHandler:
public class GlobalExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct)
{
// log the exception here
ctx.Response.StatusCode = 500;
await ctx.Response.WriteAsJsonAsync(new ProblemDetails { Title = "Something went wrong" }, ct);
return true;
}
}
Register it with AddExceptionHandler<GlobalExceptionHandler>() and AddProblemDetails(), then call app.UseExceptionHandler().
Log the full exception on the server, but never send stack traces to the client in production. Keep try/catch only where you can recover from a specific error.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Yes. Let exceptions bubble up and handle them in one place with middleware. That keeps controllers short and makes every error response look the same.
In .NET 8 the simplest way is IExceptionHandler:
Register it with
AddExceptionHandler<GlobalExceptionHandler>()andAddProblemDetails(), then callapp.UseExceptionHandler().Log the full exception on the server, but never send stack traces to the client in production. Keep try/catch only where you can recover from a specific error.