Adds logging for cancelled requests and DbUpdateExceptions

This commit is contained in:
Cyberboss
2018-09-27 15:26:19 -04:00
parent d267e4e259
commit ca0b6c6e60
@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
using Tgstation.Server.Api.Models;
@@ -12,6 +15,13 @@ namespace Tgstation.Server.Host.Core
/// </summary>
static class ApplicationBuilderExtensions
{
/// <summary>
/// Gets a <see cref="ILogger"/> from a given <paramref name="httpContext"/>
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> to get the <see cref="ILogger"/> from</param>
/// <returns>A new <see cref="ILogger"/></returns>
static ILogger GetLogger(HttpContext httpContext) => httpContext.RequestServices.GetRequiredService<ILogger<Application>>();
/// <summary>
/// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s
/// </summary>
@@ -22,12 +32,14 @@ namespace Tgstation.Server.Host.Core
throw new ArgumentNullException(nameof(applicationBuilder));
applicationBuilder.Use(async (context, next) =>
{
var logger = GetLogger(context);
try
{
await next().ConfigureAwait(false);
}
catch (DbUpdateException e)
{
logger.LogDebug("Database conflict: {0}", e.Message);
await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext
{
HttpContext = context
@@ -46,11 +58,15 @@ namespace Tgstation.Server.Host.Core
throw new ArgumentNullException(nameof(applicationBuilder));
applicationBuilder.Use(async (context, next) =>
{
var logger = GetLogger(context);
try
{
await next().ConfigureAwait(false);
}
catch (OperationCanceledException) { }
catch (OperationCanceledException)
{
logger.LogDebug("Request cancelled!");
}
});
}
}