Add first swing at UnhandledExceptionLoggerMiddleware

This commit is contained in:
Mole
2020-10-12 15:27:07 +02:00
parent 50f4d7abde
commit e44dae2fcb
3 changed files with 46 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using SixLabors.ImageSharp.Web.DependencyInjection;
using Umbraco.Web.BackOffice;
using Umbraco.Web.BackOffice.Routing;
using Umbraco.Web.BackOffice.Security;
@@ -46,6 +47,7 @@ namespace Umbraco.Extensions
app.UseUmbracoRuntimeMinification();
app.UseMiddleware<PreviewAuthenticationMiddleware>();
app.UseMiddleware<UnhandledExceptionLoggerMiddleware>();
return app;
}

View File

@@ -48,6 +48,7 @@ namespace Umbraco.Web.BackOffice.Runtime
"~/"));
composition.RegisterUnique<IIconService, IconService>();
composition.RegisterUnique<UnhandledExceptionLoggerMiddleware>();
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Umbraco.Core;
namespace Umbraco.Web.BackOffice
{
public class UnhandledExceptionLoggerMiddleware : IMiddleware
{
private readonly ILogger<UnhandledExceptionLoggerMiddleware> _logger;
public UnhandledExceptionLoggerMiddleware(ILogger<UnhandledExceptionLoggerMiddleware> logger)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var requestUri = new Uri(context.Request.GetEncodedUrl(), UriKind.RelativeOrAbsolute);
// If it's a client side request just call next and don't try to log anything
if (requestUri.IsClientSideRequest())
{
await next(context);
}
else
{
// We call the next middleware, and catch any errors that occurs in the rest of the pipeline
try
{
await next(context);
}
catch (Exception e)
{
_logger.LogError(e, "Unhandled controller exception occurred for request '{RequestUrl}'", requestUri.AbsoluteUri);
// throw the error again, just in case it gets handled (which is shouldn't)
throw;
}
}
}
}
}