using System;
using System.Text.Json;
using System.Threading.Tasks;
using Jellyfin.Api.Models.ExceptionDtos;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Server.Middleware
{
///
/// Exception Middleware.
///
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
/// Next request delegate.
/// Instance of the interface.
public ExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory.CreateLogger() ??
throw new ArgumentNullException(nameof(loggerFactory));
}
///
/// Invoke request.
///
/// Request context.
/// Task.
public async Task Invoke(HttpContext context)
{
try
{
await _next(context).ConfigureAwait(false);
}
catch (Exception ex)
{
if (context.Response.HasStarted)
{
_logger.LogWarning("The response has already started, the exception middleware will not be executed.");
throw;
}
var exceptionBody = new ExceptionDto { Message = ex.Message };
var exceptionJson = JsonSerializer.Serialize(exceptionBody);
context.Response.Clear();
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
// TODO switch between PascalCase and camelCase
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(exceptionJson).ConfigureAwait(false);
}
}
}
}