Search code examples
c#asp.net-coreexceptionelmah

Catch Exceptions Globally using ElmahCore in Aspnet core 3.0?


I am using Aspnet core 3.0 and I have configured ElmahCore for exception handling. however from their documentation, they advise to catch exceptions using

public IActionResult Test()
{
    HttpContext.RiseError(new InvalidOperationException("Test"));
    ...
}

How can I configure Elmahcore to automatically catch and log all exceptions? or Do I have to write HttpContext.RiseError everytime I want to catch and log an exception?

Like Do I have to put try catch blocks for every ActionResult and call HttpContext.RiseError() in all of my catch blocks?

Is there a way that I can configure catching and logging of exceptions using ElmahCore globally?


Solution

  • Based on @Fei-han's suggestion and this global error handling link, I am able to log exceptions globally in my production environment. In Startup.cs file, I made sure that I have an ExceptionHandler configured when my application is running in production mode like

    Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
      }
      else
      {
        app.UseExceptionHandler("/Home/Error");  
        app.UseHsts();
      }
    
      app.UseElmah();
    
      //Other configurations
    }
    

    This ensures that whenever an uncaught exception has occurred, it will call the Error Action Method of Home Controller

    Home Controller

        using Microsoft.AspNetCore.Diagnostics;
        public IActionResult Error()
        {
            var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    
            if (exceptionFeature != null)
            {
                // Get the exception that occurred
                Exception exceptionThatOccurred = exceptionFeature.Error;
                //log exception using ElmahCore
                HttpContext.RiseError(exceptionThatOccurred);
            }
    
            //Return custom error page (I have modified the default html of
            //Shared>Error.cshtml view and showed my custom error page)
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    

    Now all of my exceptions are getting logged and I am also showing a customized error page in response to an exception.