diff --git a/DigitalData.Core.Exceptions/DependencyInjection.cs b/DigitalData.Core.Exceptions/DependencyInjection.cs new file mode 100644 index 0000000..ec40485 --- /dev/null +++ b/DigitalData.Core.Exceptions/DependencyInjection.cs @@ -0,0 +1,12 @@ +using Microsoft.AspNetCore.Builder; + +namespace DigitalData.Core.Exceptions; + +public static class DependencyInjection +{ + public static IApplicationBuilder UseExceptionHandlingMiddleware(this IApplicationBuilder app) + { + app.UseMiddleware(); + return app; + } +} diff --git a/DigitalData.Core.Exceptions/DigitalData.Core.Exceptions.csproj b/DigitalData.Core.Exceptions/DigitalData.Core.Exceptions.csproj index bae5b9f..0f74356 100644 --- a/DigitalData.Core.Exceptions/DigitalData.Core.Exceptions.csproj +++ b/DigitalData.Core.Exceptions/DigitalData.Core.Exceptions.csproj @@ -6,4 +6,9 @@ enable + + + + + diff --git a/DigitalData.Core.API/ExceptionHandlingMiddleware.cs b/DigitalData.Core.Exceptions/ExceptionHandlingMiddleware.cs similarity index 90% rename from DigitalData.Core.API/ExceptionHandlingMiddleware.cs rename to DigitalData.Core.Exceptions/ExceptionHandlingMiddleware.cs index b02655d..2963c79 100644 --- a/DigitalData.Core.API/ExceptionHandlingMiddleware.cs +++ b/DigitalData.Core.Exceptions/ExceptionHandlingMiddleware.cs @@ -1,6 +1,5 @@ -namespace DigitalData.Core.API; +namespace DigitalData.Core.Exceptions; -using DigitalData.Core.Exceptions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Net; @@ -14,14 +13,14 @@ using System.Text.Json; public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; - private readonly ILogger _logger; + private readonly ILogger? _logger; /// /// Initializes a new instance of the class. /// /// The next middleware in the request pipeline. /// The logger instance for logging exceptions. - public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger? logger = null) { _next = next; _logger = logger; @@ -51,7 +50,7 @@ public class ExceptionHandlingMiddleware /// The exception that occurred. /// The logger instance for logging the exception. /// A task that represents the asynchronous operation. - private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger) + private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger? logger = null) { context.Response.ContentType = "application/json"; @@ -70,7 +69,7 @@ public class ExceptionHandlingMiddleware break; default: - logger.LogError(exception, "Unhandled exception occurred."); + logger?.LogError(exception, "Unhandled exception occurred."); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; message = "An unexpected error occurred."; break;