Exception Handling in .NET Core Web API using UseDeveloperExceptionPage & UseExceptionHandler methods

Updated on: March 24, 2021

Follow Below steps 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:

  1.     [Route("api/[controller]")]
  2.     [ApiController]
  3.     public class EmployeeController : ControllerBase
  4.     {
  5.         public IActionResult Get()
  6.         {
  7.             int a = 20, b = 0, c = a / b;
  8.             return Ok("EmpoyeeList=[{EmployeeId:1, Name:'John'}]");
  9.         }
  10.     }

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:

  1.     [Route("api/[controller]")]
  2.     [ApiController]
  3.     public class ErrorController : ControllerBase
  4.     {
  5.         public IActionResult Get()
  6.         {
  7.             return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error Occurred!");
  8.         }
  9.     }

Step 4: Add the below code in Configure() method of Startup.cs class

  1.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2.         {
  3.             if (env.IsDevelopment())
  4.             {
  5.                 app.UseDeveloperExceptionPage();
  6.             }
  7.             else
  8.             {
  9.                 app.UseExceptionHandler("/api/error/");
  10.             }

  11.             app.UseHttpsRedirection();

  12.             app.UseRouting();

  13.             app.UseEndpoints(endpoints =>
  14.             {
  15.                 endpoints.MapControllers();
  16.             });
  17.         }

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.