ExceptionMiddleware.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. using System;
  2. using System.IO;
  3. using System.Net.Mime;
  4. using System.Net.Sockets;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Common.Extensions;
  7. using MediaBrowser.Controller.Authentication;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Net;
  10. using Microsoft.AspNetCore.Hosting;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.Extensions.Hosting;
  13. using Microsoft.Extensions.Logging;
  14. namespace Jellyfin.Server.Middleware
  15. {
  16. /// <summary>
  17. /// Exception Middleware.
  18. /// </summary>
  19. public class ExceptionMiddleware
  20. {
  21. private readonly RequestDelegate _next;
  22. private readonly ILogger<ExceptionMiddleware> _logger;
  23. private readonly IServerConfigurationManager _configuration;
  24. private readonly IWebHostEnvironment _hostEnvironment;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="ExceptionMiddleware"/> class.
  27. /// </summary>
  28. /// <param name="next">Next request delegate.</param>
  29. /// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
  30. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  31. /// <param name="hostEnvironment">Instance of the <see cref="IWebHostEnvironment"/> interface.</param>
  32. public ExceptionMiddleware(
  33. RequestDelegate next,
  34. ILogger<ExceptionMiddleware> logger,
  35. IServerConfigurationManager serverConfigurationManager,
  36. IWebHostEnvironment hostEnvironment)
  37. {
  38. _next = next;
  39. _logger = logger;
  40. _configuration = serverConfigurationManager;
  41. _hostEnvironment = hostEnvironment;
  42. }
  43. /// <summary>
  44. /// Invoke request.
  45. /// </summary>
  46. /// <param name="context">Request context.</param>
  47. /// <returns>Task.</returns>
  48. public async Task Invoke(HttpContext context)
  49. {
  50. try
  51. {
  52. await _next(context).ConfigureAwait(false);
  53. }
  54. catch (Exception ex)
  55. {
  56. if (context.Response.HasStarted)
  57. {
  58. _logger.LogWarning("The response has already started, the exception middleware will not be executed.");
  59. throw;
  60. }
  61. ex = GetActualException(ex);
  62. bool ignoreStackTrace =
  63. ex is SocketException
  64. || ex is IOException
  65. || ex is OperationCanceledException
  66. || ex is SecurityException
  67. || ex is AuthenticationException
  68. || ex is FileNotFoundException;
  69. if (ignoreStackTrace)
  70. {
  71. _logger.LogError(
  72. "Error processing request: {ExceptionMessage}. URL {Method} {Url}.",
  73. ex.Message.TrimEnd('.'),
  74. context.Request.Method,
  75. context.Request.Path);
  76. }
  77. else
  78. {
  79. _logger.LogError(
  80. ex,
  81. "Error processing request. URL {Method} {Url}.",
  82. context.Request.Method,
  83. context.Request.Path);
  84. }
  85. context.Response.StatusCode = GetStatusCode(ex);
  86. context.Response.ContentType = MediaTypeNames.Text.Plain;
  87. // Don't send exception unless the server is in a Development environment
  88. var errorContent = _hostEnvironment.IsDevelopment()
  89. ? NormalizeExceptionMessage(ex.Message)
  90. : "Error processing request.";
  91. await context.Response.WriteAsync(errorContent).ConfigureAwait(false);
  92. }
  93. }
  94. private static Exception GetActualException(Exception ex)
  95. {
  96. if (ex is AggregateException agg)
  97. {
  98. var inner = agg.InnerException;
  99. if (inner != null)
  100. {
  101. return GetActualException(inner);
  102. }
  103. var inners = agg.InnerExceptions;
  104. if (inners.Count > 0)
  105. {
  106. return GetActualException(inners[0]);
  107. }
  108. }
  109. return ex;
  110. }
  111. private static int GetStatusCode(Exception ex)
  112. {
  113. switch (ex)
  114. {
  115. case ArgumentException _: return StatusCodes.Status400BadRequest;
  116. case AuthenticationException _: return StatusCodes.Status401Unauthorized;
  117. case SecurityException _: return StatusCodes.Status403Forbidden;
  118. case DirectoryNotFoundException _:
  119. case FileNotFoundException _:
  120. case ResourceNotFoundException _: return StatusCodes.Status404NotFound;
  121. case MethodNotAllowedException _: return StatusCodes.Status405MethodNotAllowed;
  122. default: return StatusCodes.Status500InternalServerError;
  123. }
  124. }
  125. private string NormalizeExceptionMessage(string msg)
  126. {
  127. // Strip any information we don't want to reveal
  128. return msg.Replace(
  129. _configuration.ApplicationPaths.ProgramSystemPath,
  130. string.Empty,
  131. StringComparison.OrdinalIgnoreCase)
  132. .Replace(
  133. _configuration.ApplicationPaths.ProgramDataPath,
  134. string.Empty,
  135. StringComparison.OrdinalIgnoreCase);
  136. }
  137. }
  138. }