(feature): webapi middlewares
This commit is contained in:
parent
c09e268e4d
commit
bbe4000095
@ -8,7 +8,7 @@
|
||||
|
||||
<!-- NuGet package metadata -->
|
||||
<PackageId>MaksIT.Core</PackageId>
|
||||
<Version>1.3.9</Version>
|
||||
<Version>1.4.0</Version>
|
||||
<Authors>Maksym Sadovnychyy</Authors>
|
||||
<Company>MAKS-IT</Company>
|
||||
<Product>MaksIT.Core</Product>
|
||||
@ -26,6 +26,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="9.0.5" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.5" />
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
using System.Text.Json;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
|
||||
namespace MaksIT.Core.Webapi.Middlewares;
|
||||
|
||||
public class ErrorHandlingMiddleware {
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<ErrorHandlingMiddleware> _logger;
|
||||
|
||||
public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger) {
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context) {
|
||||
try {
|
||||
await _next(context); // proceed to next middleware
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_logger.LogError(ex, "Unhandled exception");
|
||||
|
||||
context.Response.StatusCode = 500;
|
||||
context.Response.ContentType = "application/json";
|
||||
|
||||
var errorResponse = new {
|
||||
error = "An unexpected error occurred.",
|
||||
details = ex.Message // or omit in production
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(errorResponse);
|
||||
await context.Response.WriteAsync(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MaksIT.Core.Webapi.Middlewares;
|
||||
|
||||
public class TraceIdLoggingScopeMiddleware {
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<TraceIdLoggingScopeMiddleware> _logger;
|
||||
|
||||
public TraceIdLoggingScopeMiddleware(RequestDelegate next, ILogger<TraceIdLoggingScopeMiddleware> logger) {
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context) {
|
||||
var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier;
|
||||
|
||||
using (_logger.BeginScope(new Dictionary<string, object> { ["TraceId"] = traceId })) {
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user