Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore exception, if request was aborted #59

Merged
merged 1 commit into from
Jan 9, 2024
Merged
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
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;
}
}
}
}
Loading