jellyfin-server/Jellyfin.Api/Middleware/ExceptionMiddleware.cs

151 lines
5.1 KiB
C#
Raw Normal View History

2020-04-21 13:36:22 +00:00
using System;
using System.IO;
using System.Net.Mime;
2020-04-24 03:23:29 +00:00
using System.Net.Sockets;
2020-04-21 13:36:22 +00:00
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
2020-04-24 03:23:29 +00:00
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Hosting;
2020-04-21 13:36:22 +00:00
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
2020-04-21 13:36:22 +00:00
using Microsoft.Extensions.Logging;
2023-01-31 11:18:10 +00:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Exception Middleware.
/// </summary>
public class ExceptionMiddleware
2020-04-21 13:36:22 +00:00
{
2023-01-31 11:18:10 +00:00
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
private readonly IServerConfigurationManager _configuration;
private readonly IWebHostEnvironment _hostEnvironment;
2020-04-21 13:36:22 +00:00
/// <summary>
2023-01-31 11:18:10 +00:00
/// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
2020-04-21 13:36:22 +00:00
/// </summary>
2023-01-31 11:18:10 +00:00
/// <param name="next">Next request delegate.</param>
/// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <param name="hostEnvironment">Instance of the <see cref="IWebHostEnvironment"/> interface.</param>
public ExceptionMiddleware(
RequestDelegate next,
ILogger<ExceptionMiddleware> logger,
IServerConfigurationManager serverConfigurationManager,
IWebHostEnvironment hostEnvironment)
2020-04-21 13:36:22 +00:00
{
2023-01-31 11:18:10 +00:00
_next = next;
_logger = logger;
_configuration = serverConfigurationManager;
_hostEnvironment = hostEnvironment;
}
2020-04-21 13:36:22 +00:00
2023-01-31 11:18:10 +00:00
/// <summary>
/// Invoke request.
/// </summary>
/// <param name="context">Request context.</param>
/// <returns>Task.</returns>
public async Task Invoke(HttpContext context)
{
try
2020-04-21 13:36:22 +00:00
{
2023-01-31 11:18:10 +00:00
await _next(context).ConfigureAwait(false);
2020-04-21 13:36:22 +00:00
}
2023-01-31 11:18:10 +00:00
catch (Exception ex)
2020-04-21 13:36:22 +00:00
{
2023-01-31 11:18:10 +00:00
if (context.Response.HasStarted)
2020-04-21 13:36:22 +00:00
{
2023-01-31 11:18:10 +00:00
_logger.LogWarning("The response has already started, the exception middleware will not be executed.");
throw;
2020-04-21 13:36:22 +00:00
}
2023-01-31 11:18:10 +00:00
ex = GetActualException(ex);
2020-04-24 03:23:29 +00:00
2023-01-31 11:18:10 +00:00
bool ignoreStackTrace =
ex is SocketException
|| ex is IOException
|| ex is OperationCanceledException
|| ex is SecurityException
|| ex is AuthenticationException
|| ex is FileNotFoundException;
2020-04-24 03:23:29 +00:00
2023-01-31 11:18:10 +00:00
if (ignoreStackTrace)
{
_logger.LogError(
"Error processing request: {ExceptionMessage}. URL {Method} {Url}.",
ex.Message.TrimEnd('.'),
context.Request.Method,
context.Request.Path);
}
else
{
_logger.LogError(
ex,
"Error processing request. URL {Method} {Url}.",
context.Request.Method,
context.Request.Path);
}
2020-04-24 03:23:29 +00:00
2023-01-31 11:18:10 +00:00
context.Response.StatusCode = GetStatusCode(ex);
context.Response.ContentType = MediaTypeNames.Text.Plain;
2023-01-31 11:18:10 +00:00
// Don't send exception unless the server is in a Development environment
var errorContent = _hostEnvironment.IsDevelopment()
? NormalizeExceptionMessage(ex.Message)
: "Error processing request.";
await context.Response.WriteAsync(errorContent).ConfigureAwait(false);
2020-04-21 13:36:22 +00:00
}
2023-01-31 11:18:10 +00:00
}
2023-01-31 11:18:10 +00:00
private static Exception GetActualException(Exception ex)
{
if (ex is AggregateException agg)
{
2023-01-31 11:18:10 +00:00
var inner = agg.InnerException;
if (inner is not null)
{
2023-01-31 11:18:10 +00:00
return GetActualException(inner);
}
2023-01-31 11:18:10 +00:00
var inners = agg.InnerExceptions;
if (inners.Count > 0)
{
2023-01-31 11:18:10 +00:00
return GetActualException(inners[0]);
}
}
2023-01-31 11:18:10 +00:00
return ex;
}
private static int GetStatusCode(Exception ex)
{
switch (ex)
{
2023-01-31 11:18:10 +00:00
case ArgumentException _: return StatusCodes.Status400BadRequest;
case AuthenticationException _: return StatusCodes.Status401Unauthorized;
case SecurityException _: return StatusCodes.Status403Forbidden;
case DirectoryNotFoundException _:
case FileNotFoundException _:
case ResourceNotFoundException _: return StatusCodes.Status404NotFound;
case MethodNotAllowedException _: return StatusCodes.Status405MethodNotAllowed;
default: return StatusCodes.Status500InternalServerError;
}
2020-04-21 13:36:22 +00:00
}
2023-01-31 11:18:10 +00:00
private string NormalizeExceptionMessage(string msg)
{
// Strip any information we don't want to reveal
return msg.Replace(
_configuration.ApplicationPaths.ProgramSystemPath,
string.Empty,
StringComparison.OrdinalIgnoreCase)
.Replace(
_configuration.ApplicationPaths.ProgramDataPath,
string.Empty,
StringComparison.OrdinalIgnoreCase);
}
2020-04-21 13:36:22 +00:00
}