aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Middleware/ExceptionMiddleware.cs
diff options
context:
space:
mode:
authorShadowghost <Ghost_of_Stone@web.de>2023-01-31 12:18:10 +0100
committerShadowghost <Ghost_of_Stone@web.de>2023-02-02 18:50:33 +0100
commitf5f890e68562e55d4bed16c454c4b4305152b296 (patch)
treeb52e3b45ceb2faa446153866600b4456fed44c8b /Jellyfin.Api/Middleware/ExceptionMiddleware.cs
parent58b3945805db4f88bc069ee84013bdf85d7429b1 (diff)
Migrate to file-scoped namespaces
Diffstat (limited to 'Jellyfin.Api/Middleware/ExceptionMiddleware.cs')
-rw-r--r--Jellyfin.Api/Middleware/ExceptionMiddleware.cs215
1 files changed, 107 insertions, 108 deletions
diff --git a/Jellyfin.Api/Middleware/ExceptionMiddleware.cs b/Jellyfin.Api/Middleware/ExceptionMiddleware.cs
index 6b3aeb187..060c14f89 100644
--- a/Jellyfin.Api/Middleware/ExceptionMiddleware.cs
+++ b/Jellyfin.Api/Middleware/ExceptionMiddleware.cs
@@ -12,140 +12,139 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
-namespace Jellyfin.Api.Middleware
+namespace Jellyfin.Api.Middleware;
+
+/// <summary>
+/// Exception Middleware.
+/// </summary>
+public class ExceptionMiddleware
{
+ private readonly RequestDelegate _next;
+ private readonly ILogger<ExceptionMiddleware> _logger;
+ private readonly IServerConfigurationManager _configuration;
+ private readonly IWebHostEnvironment _hostEnvironment;
+
/// <summary>
- /// Exception Middleware.
+ /// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
/// </summary>
- public class ExceptionMiddleware
+ /// <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)
{
- private readonly RequestDelegate _next;
- private readonly ILogger<ExceptionMiddleware> _logger;
- private readonly IServerConfigurationManager _configuration;
- private readonly IWebHostEnvironment _hostEnvironment;
+ _next = next;
+ _logger = logger;
+ _configuration = serverConfigurationManager;
+ _hostEnvironment = hostEnvironment;
+ }
- /// <summary>
- /// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
- /// </summary>
- /// <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)
+ /// <summary>
+ /// Invoke request.
+ /// </summary>
+ /// <param name="context">Request context.</param>
+ /// <returns>Task.</returns>
+ public async Task Invoke(HttpContext context)
+ {
+ try
{
- _next = next;
- _logger = logger;
- _configuration = serverConfigurationManager;
- _hostEnvironment = hostEnvironment;
+ await _next(context).ConfigureAwait(false);
}
-
- /// <summary>
- /// Invoke request.
- /// </summary>
- /// <param name="context">Request context.</param>
- /// <returns>Task.</returns>
- public async Task Invoke(HttpContext context)
+ catch (Exception ex)
{
- try
+ if (context.Response.HasStarted)
{
- await _next(context).ConfigureAwait(false);
+ _logger.LogWarning("The response has already started, the exception middleware will not be executed.");
+ throw;
}
- catch (Exception ex)
- {
- if (context.Response.HasStarted)
- {
- _logger.LogWarning("The response has already started, the exception middleware will not be executed.");
- throw;
- }
- ex = GetActualException(ex);
+ ex = GetActualException(ex);
- bool ignoreStackTrace =
- ex is SocketException
- || ex is IOException
- || ex is OperationCanceledException
- || ex is SecurityException
- || ex is AuthenticationException
- || ex is FileNotFoundException;
+ bool ignoreStackTrace =
+ ex is SocketException
+ || ex is IOException
+ || ex is OperationCanceledException
+ || ex is SecurityException
+ || ex is AuthenticationException
+ || ex is FileNotFoundException;
- 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);
- }
+ 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);
+ }
- context.Response.StatusCode = GetStatusCode(ex);
- context.Response.ContentType = MediaTypeNames.Text.Plain;
+ context.Response.StatusCode = GetStatusCode(ex);
+ context.Response.ContentType = MediaTypeNames.Text.Plain;
- // 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);
- }
+ // 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);
}
+ }
- private static Exception GetActualException(Exception ex)
+ private static Exception GetActualException(Exception ex)
+ {
+ if (ex is AggregateException agg)
{
- if (ex is AggregateException agg)
+ var inner = agg.InnerException;
+ if (inner is not null)
{
- var inner = agg.InnerException;
- if (inner is not null)
- {
- return GetActualException(inner);
- }
-
- var inners = agg.InnerExceptions;
- if (inners.Count > 0)
- {
- return GetActualException(inners[0]);
- }
+ return GetActualException(inner);
}
- return ex;
- }
-
- private static int GetStatusCode(Exception ex)
- {
- switch (ex)
+ var inners = agg.InnerExceptions;
+ if (inners.Count > 0)
{
- 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;
+ return GetActualException(inners[0]);
}
}
- private string NormalizeExceptionMessage(string msg)
+ return ex;
+ }
+
+ private static int GetStatusCode(Exception ex)
+ {
+ switch (ex)
{
- // 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);
+ 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;
}
}
+
+ 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);
+ }
}