Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global exception handling in ASP.NET 5

How can I attach my own logging logic to an ASP.NET 5 application to handle each exception thrown in the business logic and lower layers?

I tried with own ILoggerProvider implementation and loggerfactory.AddProvider(new LoggerProvider(Configuration)) in Startup.cs. But it seems that it intercepts inner ASP.NET stuff, and not my thrown exceptions in lower layers.

like image 686
alek kowalczyk Avatar asked Feb 07 '15 18:02

alek kowalczyk


People also ask

What is global exception handling in ASP.NET Core?

Global exception handling with custom middleware grants the developer much broader authority and enhances the procedure. It's a block of code that can be added to the ASP.NET Core pipeline as middleware and holds our custom error handling mechanism.

What is global exception handling?

The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.

How exceptions are handled globally in C#?

An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.


1 Answers

Worked it out, by using two options:

1) ILoggerProvider Implement your own ILoggerProvider and ILogger from the namespace Microsoft.Framework.Logging Then attach it to the MVC Framework in Startup.cs add following code:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
 {
        loggerfactory.AddProvider(new YourCustomProvider());
 }

But this above option, seems to only call the Write function of the ILogger on MVC specific events, routing related and so on, it wasn't called when I threw exceptions on my lower layers, so the second option worked out:

2) Global Filter Register your own ActionFilterAttribute implementation in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new YourCustomFilter());
    });
}

It's important, that the custom filter class implements the IExceptionFilter interace:

  public class YourCustomFilter : ActionFilterAttribute, IExceptionFilter
  {
             public void OnException(ExceptionContext context)
             {
              ///logic...
             }
 }

(EDIT:) And then in the Startup class we add the filter:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc(options =>
            {
                options.Filters.Add(new YourCustomFilter());
            });
    }
like image 83
alek kowalczyk Avatar answered Oct 08 '22 01:10

alek kowalczyk