Centralized Exception Handling Without Using Try Catch Block In .Net Core 2.2 Web API

Rather than writing try catch block for each method, throwing exceptions manually and handling them, here we will use the power of .Net Core middleware to handle the exceptions at one single place, so that when an exception occurs anywhere in the code, the appropriate action can be taken. We will use UseExceptionHandler extension method that will add a middleware to the pipeline, and it will catch exceptions, log them, reset the request path, and re-execute the request if response has not already started.
 
Developer can customize the response format as well.
 
To achive this in .NetCore 2.2, this code snippet is very simple and it's just a matter of adding a few lines in your Startup.cs.
 
Simply go in Configure method and add the below code,
  1. if (env.IsDevelopment()) {  
  2.     app.UseDeveloperExceptionPage();  
  3. else {  
  4.     app.UseExceptionHandler(errorApp => errorApp.Run(async context => {  
  5.         // use Exception handler path feature to catch the exception details   
  6.         var exceptionHandlerPathFeature = context.Features.Get < IExceptionHandlerPathFeature > ();  
  7.         // log errors using above exceptionHandlerPathFeature object   
  8.         Console.WriteLine(exceptionHandlerPathFeature ? .Error);  
  9.         // Write a custom response message to API Users   
  10.         context.Response.StatusCode = "500";  
  11.         // Set a response format    
  12.         context.Response.ContentType = "application/json";  
  13.         await context.Response.WriteAsync("Some error occured.");  
  14.     }));  
  15. }  
The Console.WriteLine() is for demonstration purposes only. Here a developer can log the exceptions using any tool/package getting used in their project.
 
When any exceptions are thrown in the application this code will be executed and will produce the desired custom response in non-development environments (as in a development env we are using UseDeveloperExceptionPage() as a middleware).
 
For a deep dive, you might find this link interesting.