Compare commits
16 Commits
50c19fea31
...
87e4c1414e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87e4c1414e | ||
|
|
fd8e976e1e | ||
|
|
2c393701e4 | ||
|
|
1d50fd8e5b | ||
|
|
701c34a251 | ||
|
|
63f914d188 | ||
|
|
9ea2599553 | ||
|
|
b8995da5ea | ||
|
|
14013bc7b7 | ||
|
|
f586e9eb2f | ||
|
|
ce786a6d42 | ||
|
|
97695fb0b0 | ||
|
|
cb7b69a0a2 | ||
|
|
b38422256c | ||
|
|
9b29a49ad6 | ||
|
|
83ba492b37 |
BIN
Assets/core_icon.png
Normal file
BIN
Assets/core_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1020 KiB |
BIN
Assets/core_legacy_icon.png
Normal file
BIN
Assets/core_legacy_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace DigitalData.Core.Exceptions.Middleware;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection ConfigureGlobalExceptionHandler(this IServiceCollection services, Action<GlobalExceptionHandlerOptions>? options = null, bool addDefaultHandlers = true)
|
||||
{
|
||||
options ??= opt => { };
|
||||
|
||||
if (addDefaultHandlers)
|
||||
{
|
||||
options += opt => opt.Add(HttpExceptionHandler.Default, setAsDefault: true);
|
||||
options += opt => opt.Add(HttpExceptionHandler.DefaultBadRequest);
|
||||
options += opt => opt.Add(HttpExceptionHandler.DefaultNotFound);
|
||||
}
|
||||
return services.Configure(options);
|
||||
}
|
||||
|
||||
public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
|
||||
{
|
||||
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<!-- NuGet Package Metadata -->
|
||||
<PackageId>DigitalData.Core.Exceptions.Middleware</PackageId>
|
||||
<Authors>Digital Data GmbH</Authors>
|
||||
<Company>Digital Data GmbH</Company>
|
||||
<Product>DigitalData.Core.Exceptions.Middleware</Product>
|
||||
<Description>Provides middleware components for standardized exception handling and error response formatting in ASP.NET Core applications.</Description>
|
||||
<PackageTags>digital data core exceptions middleware</PackageTags>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<Copyright>Copyright 2025</Copyright>
|
||||
<PackageProjectUrl></PackageProjectUrl>
|
||||
<RepositoryUrl>http://git.dd:3000/AppStd/WebCoreModules.git</RepositoryUrl>
|
||||
<PackAsTool>False</PackAsTool>
|
||||
<PackageIcon>core_icon.png</PackageIcon>
|
||||
<Version>1.0.0</Version>
|
||||
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="..\Assets\core_icon.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0'">
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.1" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net9.0'">
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DigitalData.Core.Exceptions\DigitalData.Core.Exceptions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@ -0,0 +1,52 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DigitalData.Core.Exceptions.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware for handling exceptions globally in the application.
|
||||
/// Captures exceptions thrown during the request pipeline execution,
|
||||
/// logs them, and returns an appropriate HTTP response with a JSON error message.
|
||||
/// </summary>
|
||||
public class GlobalExceptionHandlerMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
private readonly ILogger<GlobalExceptionHandlerMiddleware>? _logger;
|
||||
|
||||
private readonly GlobalExceptionHandlerOptions? _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GlobalExceptionHandlerMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
/// <param name="logger">The logger instance for logging exceptions.</param>
|
||||
public GlobalExceptionHandlerMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlerMiddleware>? logger = null, IOptions<GlobalExceptionHandlerOptions>? options = null)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
_options = options?.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes the middleware to handle the HTTP request.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context of the current request.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context); // Continue down the pipeline
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if(ex.GetType() == typeof(Exception))
|
||||
_options?.DefaultHandler?.HandleExceptionAsync.Invoke(context, ex, _logger);
|
||||
|
||||
if (_options?.Handlers.TryGetValue(ex.GetType(), out var handler) ?? false)
|
||||
handler?.HandleExceptionAsync.Invoke(context, ex, _logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
namespace DigitalData.Core.Exceptions.Middleware;
|
||||
|
||||
public class GlobalExceptionHandlerOptions
|
||||
{
|
||||
internal readonly Dictionary<Type, HttpExceptionHandler> Handlers = new();
|
||||
|
||||
internal HttpExceptionHandler? DefaultHandler { get; private set; }
|
||||
|
||||
public GlobalExceptionHandlerOptions Add(HttpExceptionHandler handler, bool setAsDefault = false)
|
||||
{
|
||||
if (setAsDefault)
|
||||
DefaultHandler = handler;
|
||||
else
|
||||
Handlers[handler.ExceptionType] = handler;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,42 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DigitalData.Core.Exceptions.Middleware;
|
||||
|
||||
public record HttpExceptionHandler(Type ExceptionType, Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync)
|
||||
{
|
||||
#region Alternative generator methods
|
||||
public static HttpExceptionHandler Create<TException>(Func<HttpContext, Exception, ILogger?, Task> HandleExceptionAsync) where TException : Exception
|
||||
=> new HttpExceptionHandler(typeof(TException), HandleExceptionAsync);
|
||||
|
||||
public static HttpExceptionHandler Create<TException>(HttpStatusCode statusCode, Func<Exception, string> messageFactory) where TException : Exception
|
||||
=> Create<TException>(
|
||||
async (context, ex, logger) =>
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = (int)statusCode;
|
||||
var message = messageFactory(ex);
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(new { message }));
|
||||
}
|
||||
);
|
||||
#endregion
|
||||
|
||||
#region Default handlers
|
||||
public static readonly Func<Exception, string> DefaultMessageFactory = ex => ex.Message;
|
||||
|
||||
public static HttpExceptionHandler DefaultBadRequest => Create<BadRequestException>(HttpStatusCode.BadRequest, DefaultMessageFactory);
|
||||
|
||||
public static HttpExceptionHandler DefaultNotFound => Create<NotFoundException>(HttpStatusCode.NotFound, DefaultMessageFactory);
|
||||
|
||||
public static HttpExceptionHandler Default => Create<Exception>(
|
||||
async (context, ex, logger) =>
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||
var message = "An unexpected error occurred.";
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(new { message }));
|
||||
});
|
||||
#endregion
|
||||
};
|
||||
@ -1,12 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
|
||||
namespace DigitalData.Core.Exceptions;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
|
||||
{
|
||||
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@ -4,8 +4,31 @@
|
||||
<TargetFrameworks>net7.0;net8.0;net9.0</TargetFrameworks>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<!-- NuGet Package Metadata -->
|
||||
<PackageId>DigitalData.Core.Exceptions</PackageId>
|
||||
<Authors>Digital Data GmbH</Authors>
|
||||
<Company>Digital Data GmbH</Company>
|
||||
<Product>DigitalData.Core.Exceptions</Product>
|
||||
<Description>This package contains exceptions for the DigitalData.Core library</Description>
|
||||
<PackageTags>digital data core exceptions</PackageTags>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<Copyright>Copyright 2025</Copyright>
|
||||
<PackageProjectUrl></PackageProjectUrl>
|
||||
<RepositoryUrl>http://git.dd:3000/AppStd/WebCoreModules.git</RepositoryUrl>
|
||||
<PackAsTool>False</PackAsTool>
|
||||
<PackageIcon>core_icon.png</PackageIcon>
|
||||
<Version>1.0.0</Version>
|
||||
<AssemblyVersion>1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="..\Assets\core_icon.png">
|
||||
<Pack>True</Pack>
|
||||
<PackagePath>\</PackagePath>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
|
||||
|
||||
@ -1,83 +0,0 @@
|
||||
namespace DigitalData.Core.Exceptions;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware for handling exceptions globally in the application.
|
||||
/// Captures exceptions thrown during the request pipeline execution,
|
||||
/// logs them, and returns an appropriate HTTP response with a JSON error message.
|
||||
/// </summary>
|
||||
public class GlobalExceptionHandlerMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<GlobalExceptionHandlerMiddleware>? _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GlobalExceptionHandlerMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
/// <param name="logger">The logger instance for logging exceptions.</param>
|
||||
public GlobalExceptionHandlerMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlerMiddleware>? logger = null)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invokes the middleware to handle the HTTP request.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context of the current request.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context); // Continue down the pipeline
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await HandleExceptionAsync(context, ex, _logger);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles exceptions by logging them and writing an appropriate JSON response.
|
||||
/// </summary>
|
||||
/// <param name="context">The HTTP context of the current request.</param>
|
||||
/// <param name="exception">The exception that occurred.</param>
|
||||
/// <param name="logger">The logger instance for logging the exception.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger? logger = null)
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
|
||||
string message;
|
||||
|
||||
switch (exception)
|
||||
{
|
||||
case BadRequestException badRequestEx:
|
||||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||||
message = badRequestEx.Message;
|
||||
break;
|
||||
|
||||
case NotFoundException notFoundEx:
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
message = notFoundEx.Message;
|
||||
break;
|
||||
|
||||
default:
|
||||
logger?.LogError(exception, "Unhandled exception occurred.");
|
||||
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||
message = "An unexpected error occurred.";
|
||||
break;
|
||||
}
|
||||
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(new
|
||||
{
|
||||
message
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
using DigitalData.Core.Abstractions;
|
||||
using DigitalData.Core.Application;
|
||||
using DigitalData.Core.Application.Interfaces.Repository;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@ -15,7 +16,7 @@ namespace DigitalData.Core.Infrastructure
|
||||
/// It leverages the EF Core's DbContext and DbSet to perform these operations.
|
||||
/// </remarks>
|
||||
public class CRUDRepository<TEntity, TId, TDbContext> : ICRUDRepository<TEntity, TId>
|
||||
where TEntity : class, IUnique<TId>
|
||||
where TEntity : class
|
||||
where TDbContext : DbContext
|
||||
{
|
||||
protected readonly TDbContext _dbContext;
|
||||
@ -107,6 +108,6 @@ namespace DigitalData.Core.Infrastructure
|
||||
/// If there are multiple entities with the same identifier, they will all be counted.
|
||||
/// The default implementation assumes that the identifier is unique for each entity.
|
||||
/// </remarks>
|
||||
public virtual async Task<int> CountAsync(TId id) => await _dbSet.Where(e => e.Id!.Equals(id)).CountAsync();
|
||||
public virtual async Task<int> CountAsync(TId id) => await _dbSet.Where(e => e.GetId().Equals(id)).CountAsync();
|
||||
}
|
||||
}
|
||||
@ -41,6 +41,16 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastru
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.Exceptions", "DigitalData.Core.Exceptions\DigitalData.Core.Exceptions.csproj", "{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DigitalData.Core.Exceptions.Middleware", "DigitalData.Core.Exceptions.Middleware\DigitalData.Core.Exceptions.Middleware.csproj", "{2336AE61-A21D-437E-A11B-367D008A64B2}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exceptions", "Exceptions", "{8C3AF25D-81D9-4651-90CA-BF0BD2A03EA7}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "assets", "assets", "{0A27EA70-74F4-48FB-881C-D741F2FCD456}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Assets\core_icon.png = Assets\core_icon.png
|
||||
Assets\core_legacy_icon.png = Assets\core_legacy_icon.png
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -94,18 +104,22 @@ Global
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9BC2DEC5-E89D-48CC-9A51-4D94496EE4A6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Debug|Any CPU.Build.0 = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Debug|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Debug|Any CPU.Build.0 = Release|Any CPU
|
||||
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CE00E1F7-2771-4D9C-88FB-E564894E539E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Debug|Any CPU.Build.0 = Release|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2336AE61-A21D-437E-A11B-367D008A64B2}.Debug|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2336AE61-A21D-437E-A11B-367D008A64B2}.Debug|Any CPU.Build.0 = Release|Any CPU
|
||||
{2336AE61-A21D-437E-A11B-367D008A64B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2336AE61-A21D-437E-A11B-367D008A64B2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -127,7 +141,9 @@ Global
|
||||
{C9266749-9504-4EA9-938F-F083357B60B7} = {72CBAFBA-55CC-49C9-A484-F8F4550054CB}
|
||||
{CE00E1F7-2771-4D9C-88FB-E564894E539E} = {41795B74-A757-4E93-B907-83BFF04EEE5C}
|
||||
{41795B74-A757-4E93-B907-83BFF04EEE5C} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
{BAEF6CC9-4FE2-4E3F-9D32-911C9E8CCFB4} = {8C3AF25D-81D9-4651-90CA-BF0BD2A03EA7}
|
||||
{2336AE61-A21D-437E-A11B-367D008A64B2} = {8C3AF25D-81D9-4651-90CA-BF0BD2A03EA7}
|
||||
{8C3AF25D-81D9-4651-90CA-BF0BD2A03EA7} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {8E2C3187-F848-493A-9E79-56D20DDCAC94}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user