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,
if (env.IsDevelopment()) {  
    app.UseDeveloperExceptionPage();  
} else {  
    app.UseExceptionHandler(errorApp => errorApp.Run(async context => {  
        // use Exception handler path feature to catch the exception details   
        var exceptionHandlerPathFeature = context.Features.Get < IExceptionHandlerPathFeature > ();  
        // log errors using above exceptionHandlerPathFeature object   
        Console.WriteLine(exceptionHandlerPathFeature ? .Error);  
        // Write a custom response message to API Users   
        context.Response.StatusCode = "500";  
        // Set a response format    
        context.Response.ContentType = "application/json";  
        await context.Response.WriteAsync("Some error occured.");  
    }));  
}  


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).

HostForLIFE.eu ASP.NET 4.8 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.