Skip to content

Commit 2f096fe

Browse files
committed
Add logs in the exception filter.
1 parent 4c3cc03 commit 2f096fe

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/Initium/Filters/ApiExceptionFilter.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1+
using System.Diagnostics;
12
using System.Net;
23
using Microsoft.AspNetCore.Mvc.Filters;
34
using Initium.Exceptions;
45
using Initium.Helpers;
56
using Initium.Response;
7+
using Microsoft.Extensions.Logging;
68

79
namespace Initium.Filters;
810

911
/// <summary>
1012
/// A filter that handles exceptions and transforms them into a standardized <see cref="ApiResponse"/>.
1113
/// </summary>
12-
internal class ApiExceptionFilter : IExceptionFilter
14+
internal class ApiExceptionFilter(ILogger<ApiExceptionFilter> logger) : IExceptionFilter
1315
{
1416
/// <summary>
1517
/// Handles exceptions that occur during the execution of an action.
@@ -19,6 +21,9 @@ internal class ApiExceptionFilter : IExceptionFilter
1921
/// <param name="context">The context for the exception.</param>
2022
public void OnException(ExceptionContext context)
2123
{
24+
// Create a stopwatch for logs.
25+
var stopwatch = Stopwatch.StartNew();
26+
2227
// Start building the ApiResponse using the Fluent Builder
2328
var apiResponseBuilder = ApiResponseBuilder.CreateFromContext(context.HttpContext);
2429

@@ -45,5 +50,8 @@ public void OnException(ExceptionContext context)
4550
.WithStatusCode(statusCode)
4651
.WithMessage(message)
4752
.BuildAsJsonResult();
53+
54+
// Logs the details of the current HTTP request.
55+
LoggingHelper.LogRequest(logger, context.HttpContext, statusCode, stopwatch.ElapsedMilliseconds);
4856
}
4957
}

0 commit comments

Comments
 (0)