Exceptionhandling mit ASP.NET Core 1.0

Dank der OWIN Pipeline in ASP.NET Core 1 lassen sich Exceptions einfach mit einer Middleware abfangen. Dies hat den Vorteil, dass Fehler auch behandelt werden, die ausserhalb eines MVC-Controllers auftreten.

Als erstes erstellt man eine eigene Middleware. Der Konstruktor nimmt als Parameter ein RequestDelegate und ein Objekt vom Typ ILoggerFactory entgegen. Die ASP.NET Core Runtime stellt dabei sicher, dass die beiden Parameter automatisch per Dependency Injection übergeben werden.

Der Try-Catch-Block um den RequestDelegate _next, kapselt dabei den Aufruf auf die nächste Middleware innerhalb der OWIN Pipeline und stellt sicher, dass ein möglicher Fehler abgefangen wird.

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Logging;

public class GlobalExceptionLogger
{
    private readonly ILogger _logger;
    private readonly RequestDelegate _next;

    public GlobalExceptionLogger(RequestDelegate next, ILoggerFactory loggerfactory)
    {
        _next = next;
        _logger = loggerfactory.CreateLogger<GlobalExceptionLogger>();
    }

    public async Task Invoke(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            _logger.LogError(String.Format("***** UNHANDLED EXCEPTION *****\r\n{0}", ex));
            throw;
        }
    }
}

public static class GlobalExceptionLoggerExtensions
{
    public static IApplicationBuilder UseGlobalExceptionLogger(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<GlobalExceptionLogger>();
    }
}

Die Registrierung der Middleware erfolgt mit Hilfe der Extensions-Methode UseGlobalExceptionLogger in der Startup-Klasse.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseIISPlatformHandler();

        app.UseGlobalExceptionLogger();

        app.UseWelcomePage();
    }

    public static void Main(string[] args) => WebApplication.Run<Startup>(args);

Ein lauffähiges Beispiel-Projekt ist auf GitHub abgelegt.