Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 5: What is the recommended approach to catch and log all unhandled exceptions?

I'm building an api app. In the old ASP.NET there was Application_Error() to catch all unhandled exceptions

protected void Application_Error()
{
    var exception = Server.GetLastError();
    _logger.FatalException("Fatal error.", exception);
}

What should be used in ASP.NET 5?

like image 781
Boris Lipschitz Avatar asked Jan 06 '16 05:01

Boris Lipschitz


People also ask

What is the best way to handle exceptions globally in ASP NET core and or ASP.NET MVC?

Use the UseExceptionHandler middleware in ASP.NET Core So, to implement the global exception handler, we can use the benefits of the ASP.NET Core build-in Middleware. A middleware is indicated as a software component inserted into the request processing pipeline which handles the requests and responses.

What are the 3 approaches to handling exceptions in a web application C#?

try catch finally 2. Use error events to deal with exceptions within the scope of an object. Page_Error Global_Error Application_Error 3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.


1 Answers

The solution is to add a custom filter. This is how it could be done:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => options.Filters.Add(new MyExceptionFilter()));
}

Now the custom filter should derive from IExceptionFilter:

public class MyExceptionFilter : ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {

    }
}

Unfortunately, it doesn't catch exceptions during Startup.Configuration()

like image 120
Boris Lipschitz Avatar answered Sep 28 '22 02:09

Boris Lipschitz