Exception Handling in .NET Core Web API using UseDeveloperExceptionPage & UseExceptionHandler methods
With .NET Core, there is an easy way to handle Exception in our application and show proper error message to the user in the response. .NET Core has provided services to handle Exception, which we can use in our application's Startup.cs class. Based on the environment of the application whether it is Production or Developer, we can handle error and display custom error messages, following steps help you to Handle Exception in .NET Core Web API and show Exception message wherever exception occurs during any Web API method request:
Step 1: Create .NET Coe Web API project using below .NET CLI command or from Visual Studio Editor as shown below:
dotnet new webapi -o EmployeeManagementAPI
Above .NET CLI command creates .NET Core Web API application with output directory as EmployeeManagementAPI, we can create .NET Core Web API application from Visual Studio Editor as shown below:
Visual Studio => Create New Project window, select "ASP.NET Core Web API" option and click on Next button, specify the Project Name, Location & Solution Name in the fields and click on Next button, In the next window, select the Target Framework & Authentication Type and click on Create button to create the Project
Step 2: Add new EmployeeController.cs Web API file and add the below code:
- [Route("api/[controller]")]
- [ApiController]
- public class EmployeeController : ControllerBase
- {
- public IActionResult Get()
- {
- int a = 20, b = 0, c = a / b;
- return Ok("EmpoyeeList=[{EmployeeId:1, Name:'John'}]");
- }
- }
As you can see in the above code, we have added "Divide by zero" exception on line number 7, when calling Get() method, it will throw the exception at line number 7 and come out of execution and in the output, it will display nothing and user will not know what's caused the execution stopped. Now, to handle the Exception and let user know about Exception, add the ErrorController and write code in Configure() method of Startup.cs class as shown below:
Step 3: Add new ErrorController.cs Web API file and add the below code:
- [Route("api/[controller]")]
- [ApiController]
- public class ErrorController : ControllerBase
- {
- public IActionResult Get()
- {
- return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Occurred!");
- }
- }
Step 4: Add the below code in Configure() method of Startup.cs class
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseExceptionHandler("/api/error/");
- }
- app.UseHttpsRedirection();
- app.UseRouting();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
Step 5: Now run the project, using .NET CLI command or using Visual Studio:
dotnet run
When you set ASPNETCORE_ENVIRONMENT to "Development", it will call UseDeveloperExceptionPage() method and it will show output as below whenever any exception is thrown throughout the application:
And when Environment is set as Production, then it will call ErrorController ("/api/error/") and show the below output:
You can add the Exception Handling as shown above and show proper message on exception during execution of any of the Web API of this application.