Skip to content

Commit

Permalink
Adds Exception Middleware
Browse files Browse the repository at this point in the history
* Adds ExceptionMiddleware

* Adds Exception Middleware unit tests
  • Loading branch information
Chingling152 authored May 20, 2024
1 parent d53e0db commit 239db37
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 32 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using FinancialHub.Core.Infra.Logs.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

namespace FinancialHub.Core.Infra.Logs.Extensions.Configurations
{
Expand All @@ -11,10 +9,5 @@ public static IServiceCollection AddCoreLogging(this IServiceCollection services
services.AddLogging();
return services;
}

public static IApplicationBuilder UseLogRequest(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LogMiddleware>();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace FinancialHub.Core.Infra.Logs.Middlewares
namespace FinancialHub.Core.WebApi.Middlewares
{
public class LogMiddleware
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger<LogMiddleware> logger;
private readonly ILogger<ExceptionMiddleware> logger;

public LogMiddleware(RequestDelegate next, ILogger<LogMiddleware> logger)
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
this.next = next;
this.logger = logger;
Expand All @@ -25,13 +25,23 @@ public async Task InvokeAsync(HttpContext context)
}
catch (Exception exception)
{
var status = context.Response.StatusCode;
this.logger.LogError(
exception,
"[{request}] - {path} error with message {message} and status {status}",
method, path, exception.Message, status
"[{request}] - {path} error with message {message}",
method, path, exception.Message
);
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(
new
{
HasError = true,
Error = new
{
Code = 500,
exception.Message,
}
}
);
throw;
}
finally
{
Expand Down
31 changes: 15 additions & 16 deletions src/api/core/FinancialHub.Core.WebApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using FinancialHub.Core.Resources.Extensions;
using FinancialHub.Core.Infra.Data.Extensions.Configurations;
using FinancialHub.Core.Infra.Logs.Extensions.Configurations;
using FinancialHub.Core.WebApi.Middlewares;

namespace FinancialHub.Core.WebApi
{
Expand All @@ -23,21 +24,19 @@ public Startup(IConfiguration configuration)

public void ConfigureServices(IServiceCollection services)
{
services.AddApiConfigurations();
services.AddApiDocs();
services.AddApiLogging();

services.AddHttpLogging(logging =>
{
logging.LoggingFields = Microsoft.AspNetCore.HttpLogging.HttpLoggingFields.All;
});

services.AddCoreResources();
services.AddCoreServices();
services.AddCoreInfra();
services.AddRepositories(Configuration);

services.AddMvc().AddNewtonsoftJson();
services
.AddApiConfigurations()
.AddApiDocs()
.AddApiLogging();

services.AddCoreResources()
.AddCoreServices()
.AddCoreInfra()
.AddRepositories(Configuration);

services
.AddMvc()
.AddNewtonsoftJson();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Expand All @@ -50,7 +49,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
}

app.UseRouting();
app.UseLogRequest();
app.UseMiddleware<ExceptionMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using FinancialHub.Core.WebApi.Middlewares;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text.Json;

namespace FinancialHub.Core.WebApi.Tests.Middleware
{
public class ExceptionMiddlewareTests
{
private ILogger<ExceptionMiddleware> logger;

[SetUp]
public void Setup()
{
this.logger = new Mock<ILogger<ExceptionMiddleware>>().Object;
}

[Test]
public void InvokeAsync_SuccessRequest_ShouldNotThrowException()
{
static Task next(HttpContext hc) => Task.CompletedTask;
var middleware = new ExceptionMiddleware(next, this.logger);
var context = new DefaultHttpContext();

Assert.That(
async () => await middleware.InvokeAsync(context),
Throws.Nothing
);
}

[Test]
public async Task InvokeAsync_SuccessRequest_ShouldNotChangePayload()
{
static Task next(HttpContext hc) => Task.CompletedTask;

var middleware = new ExceptionMiddleware(next, this.logger);

var response = new Mock<HttpResponse>();
response
.SetupGet(x => x.StatusCode)
.Returns(200);
var context = new Mock<HttpContext>();
context
.SetupGet(x => x.Response)
.Returns(response.Object);
context
.SetupGet(x => x.Request)
.Returns(new DefaultHttpContext().Request);

var defaultContext = new DefaultHttpContext();

await middleware.InvokeAsync(context.Object);

Assert.That(response.Object.StatusCode, Is.EqualTo(200));
}

[Test]
public void InvokeAsync_RequestWithUnhandledError_ShouldNotThrowException()
{
static Task next(HttpContext hc) => Task.CompletedTask;
var middleware = new ExceptionMiddleware(next, this.logger);
var context = new DefaultHttpContext();

Assert.That(
async () => await middleware.InvokeAsync(context),
Throws.Nothing
);
}

[Test]
public async Task InvokeAsync_RequestWithUnhandledError_ShouldChangeStatusTo500()
{
static Task next(HttpContext hc) => Task.FromException(new Exception("Error"));

var middleware = new ExceptionMiddleware(next, this.logger);
var context = new DefaultHttpContext();

await middleware.InvokeAsync(context);

Assert.That(context.Response.StatusCode, Is.EqualTo(500));
}
}
}

0 comments on commit 239db37

Please sign in to comment.