Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/BuildingBlocks/Web/Exceptions/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
using FSH.Framework.Core.Exceptions;
using FSH.Framework.Core.Context;
using FSH.Framework.Core.Exceptions;
using FSH.Framework.Shared.Multitenancy;
using Finbuckle.MultiTenant.Abstractions;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog.Context;

namespace FSH.Framework.Web.Exceptions;

public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
: IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
Expand Down Expand Up @@ -62,12 +67,24 @@ public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception e

httpContext.Response.StatusCode = statusCode;

var multiTenantContextAccessor = httpContext.RequestServices.GetRequiredService<IMultiTenantContextAccessor<AppTenantInfo>>();
var currentUser = httpContext.RequestServices.GetRequiredService<ICurrentUser>();

string? tenantId = multiTenantContextAccessor?.MultiTenantContext?.TenantInfo?.Id;
Guid userId = currentUser.GetUserId();

LogContext.PushProperty("tenant_id", tenantId);
LogContext.PushProperty("user_id", userId);
LogContext.PushProperty("exception_title", problemDetails.Title);
LogContext.PushProperty("exception_detail", problemDetails.Detail);
LogContext.PushProperty("exception_statusCode", problemDetails.Status);
LogContext.PushProperty("exception_stackTrace", exception.StackTrace);

logger.LogError("Exception at {Path} - {Detail}", httpContext.Request.Path, problemDetails.Detail);
logger.LogError("Exception at {Path} (Tenant: {TenantId}, User: {UserId}) - {Detail}",
httpContext.Request.Path,
tenantId ?? "None",
userId == Guid.Empty ? "Anonymous" : userId.ToString(),
problemDetails.Detail);

await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken).ConfigureAwait(false);
return true;
Expand Down
57 changes: 57 additions & 0 deletions src/Tests/Generic.Tests/Exceptions/GlobalExceptionHandlerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using FSH.Framework.Core.Context;
using FSH.Framework.Shared.Multitenancy;
using FSH.Framework.Web.Exceptions;
using Finbuckle.MultiTenant.Abstractions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Xunit;

namespace Generic.Tests.Exceptions;

public class GlobalExceptionHandlerTests
{
private readonly ILogger<GlobalExceptionHandler> _logger = Substitute.For<ILogger<GlobalExceptionHandler>>();
private readonly IMultiTenantContextAccessor<AppTenantInfo> _multiTenantContextAccessor = Substitute.For<IMultiTenantContextAccessor<AppTenantInfo>>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
private readonly GlobalExceptionHandler _handler;

public GlobalExceptionHandlerTests()
{
_handler = new GlobalExceptionHandler(_logger);
}

[Fact]
public async Task TryHandleAsync_Should_IncludeTenantAndUserInLogs()
{
// Arrange
var context = new DefaultHttpContext();
var services = Substitute.For<IServiceProvider>();
context.RequestServices = services;

var exception = new Exception("Test exception");
var cancellationToken = CancellationToken.None;

var tenantInfo = new AppTenantInfo { Id = "test-tenant" };
var multiTenantContext = Substitute.For<IMultiTenantContext<AppTenantInfo>>();
multiTenantContext.TenantInfo.Returns(tenantInfo);
_multiTenantContextAccessor.MultiTenantContext.Returns(multiTenantContext);

services.GetService(typeof(IMultiTenantContextAccessor<AppTenantInfo>)).Returns(_multiTenantContextAccessor);
services.GetService(typeof(ICurrentUser)).Returns(_currentUser);

var userId = Guid.NewGuid();
_currentUser.GetUserId().Returns(userId);

// Act
var result = await _handler.TryHandleAsync(context, exception, cancellationToken);

// Assert
result.ShouldBeTrue();
context.Response.StatusCode.ShouldBe(StatusCodes.Status500InternalServerError);

// Verify logger was called with tenant and user info
_logger.ReceivedWithAnyArgs().LogError(default);
}
}
2 changes: 2 additions & 0 deletions src/Tests/Generic.Tests/Generic.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</PackageReference>
<PackageReference Include="FluentValidation" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
Expand All @@ -24,6 +25,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\BuildingBlocks\Shared\Shared.csproj" />
<ProjectReference Include="..\..\BuildingBlocks\Web\Web.csproj" />
<ProjectReference Include="..\..\Modules\Auditing\Modules.Auditing\Modules.Auditing.csproj" />
<ProjectReference Include="..\..\Modules\Auditing\Modules.Auditing.Contracts\Modules.Auditing.Contracts.csproj" />
<ProjectReference Include="..\..\Modules\Identity\Modules.Identity\Modules.Identity.csproj" />
Expand Down