Using exception handlers in an ASP.NET Core Web API
Learn how to add exception handlers in an ASP.NET Core Web API.
You can read more about exception handlers, or watch the video:
Download the code example
You'll need to fill out the code example form. We will send you an email where you can download the code example.
Software
This is the software that will need to be installed onto your machine.
Visual Studio 2026. Version 18.0.0 or above. It will work with the free community version.
.NET 10 SDK. Version 10.0.0 or above.
The application
Open up RoundTheCode.ExceptionHandlerSetup.slnx, and run the application. The Swagger documentation will load at https://localhost:7009/swagger with these endpoints:
/api/products/validation-exception (POST)- Throws a 400 Bad Request response. Try it with this request body:{ "name": "", "price": -0.1 }/api/products/unauthorized-exception (POST)- Throws a 401 Unauthorized response./api/products/global-exception (POST)- Throws a 500 Internal Server error response.
If you want to try out the exception handler in ExceptionHandlingMiddleware, uncomment it in Program.cs.
Download this code example
Enter your email and we'll send you a download link.
Latest code examples
Download a C# code example to help you learn variables, types, conditionals, arrays, lists, loops, classes, structs, interfaces, enums and static classes.
See how keyset and offset pagination are implemented in EF Core, how indexes affect performance, so you decide which approach suits your application.
Download this code example
Enter your email and we'll send you a download link.