Skip to main content
most productive way to handle exception in ASPNET Core

The most productive way to handle exception in ASP.NET Core

A few days ago, a tweet from Marcos Besteiro got my attention. He tweeted, “Most productive exception handler ever”. Here is the actual tweet.
https://twitter.com/MarcosBL/status/728442224132825089

It’s indeed the most productive exception handling idea that I came across. This is what we as developers do most of the times when there is an exception. We simply copy and paste the exception on Google/Bing and got the answers on StackOverflow. And this idea will definitely save the efforts of copy-paste and then searching for help. As earlier, I posted about Global Exception Handling in ASP.NET Core WEB API and thought of implementing the same idea with ASP.NET Core.

Coolest way to handle exception in ASP.NET Core

If you have not read Global Exception Handling in ASP.NET Core WEB API yet, then please read it. As I am using the same code to show you how to implement this idea with ASP.NET Core. The idea to open StackOverflow page for exception help should only be done for development not for production version.

First, identify the environment. And this can be done via IHostingEnvironment service. To use IHostingEnvironment service in CustomExceptionFilter class, define a constructor and inject IHostingEnvironment service and assign it to a variable. Like this,

private readonly IHostingEnvironment _hostingEnvironment;
public CustomExceptionFilter(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}

And then in OnException() method, write following code.

if (_hostingEnvironment.IsDevelopment())
{
  var URL = "https://stackoverflow.com/search?q=[asp.net-core]" 
             + Uri.EscapeDataString(context.Exception.Message);
  URL = String.Format("<script>window.open('{0}','_blank')</script>", URL);
  HttpResponse response = context.HttpContext.Response;
  response.WriteAsync(URL);
}
  • Uri.EscapeDataString: is used to escape characters so that URL is properly formed.
  • In the StackOverFlow URL, the part after q= in square bracket, is the tag name. Since we are using ASP.NET Core, so I put [asp.net-core]. This will help to search for help in all the posts tagged under [asp.net-core]. So if you want to search within C# tag, then use . And you can remove the tag name.

That’s it. So now when any exception occurs during development phase, your application will automatically open up the help for you to fix it. You can also get wwwroot folder path using IHostingEnvironment service. Read Get application base and wwwroot path in ASP.NET Core RC2

Thank you for reading and I hope it helped you. Keep visiting this blog and share this in your network.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *