Skip to content

Commit

Permalink
Merge pull request #60 from wemogy/main
Browse files Browse the repository at this point in the history
Release
  • Loading branch information
SebastianKuesters authored Jan 9, 2024
2 parents d24ce5a + 96bccbc commit f16176b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Wemogy.AspNet.Tests/Middlewares/ErrorHandlerMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentValidation;
Expand Down Expand Up @@ -84,4 +85,33 @@ await middleware.InvokeAsync(
// Assert
context.Response.StatusCode.Should().Be((int)HttpStatusCode.BadRequest);
}

[Fact]
public async Task CanceledRequestShouldBeIgnored()
{
// Arrange
var abortedCts = new CancellationTokenSource();
var context = new DefaultHttpContext
{
RequestServices = new ServiceCollection()
.AddLogging()
.BuildServiceProvider(),
RequestAborted = abortedCts.Token
};
var next = new RequestDelegate(
c =>
{
// simulate that somewhere in the pipeline we are checking for cancellation
c.RequestAborted.ThrowIfCancellationRequested();
return Task.CompletedTask;
});
var middleware = new ErrorHandlerMiddleware(next);

// Act
abortedCts.Cancel(); // simulate that the request was aborted
var exception = await Record.ExceptionAsync(() => middleware.InvokeAsync(context));

// Assert
exception.Should().BeNull();
}
}
12 changes: 12 additions & 0 deletions src/Wemogy.AspNet/Middlewares/ErrorHandlerMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Net;
using System.Threading.Tasks;
using FluentValidation;
Expand Down Expand Up @@ -66,6 +67,17 @@ public async Task InvokeAsync(HttpContext context)
response.StatusCode = (int)HttpStatusCode.BadRequest;
await response.WriteAsJsonAsync(exception.Errors);
}

// Catch OperationCanceledException, when the request is aborted
catch (OperationCanceledException)
{
if (context.RequestAborted.IsCancellationRequested)
{
return;
}

throw;
}
}
}
}

0 comments on commit f16176b

Please sign in to comment.