Catch OperationCanceledException in Exception Middleware in asp.net core 5.0

babak fakhriloo 41 Reputation points
2021-06-28T12:46:34.21+00:00

I have defined a middle-ware as below :

 public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _requestDelegate;

        public ExceptionHandlerMiddleware(RequestDelegate requestDelegate) => _requestDelegate = requestDelegate;

        public async Task InvokeAsync(HttpContext httpContext, ILogger<ExceptionHandlerMiddleware> logger)
        {

            ObjectResult errorResponse;

            try
            {
                await _requestDelegate(httpContext);
                return;
            }           
            catch (OperationCanceledException expOp)
            {
                errorResponse // add some data for final response ;
            }
            catch (Exception exception)
            {
                 .. 
             }

             var result = JsonSerializer.Serialize(errorResponse);

            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)errorResponse.StatusCode;


            await httpContext.Response.WriteAsync(result);

        }
    }

This works for all types of exceptions, but not for OperationCanceledException.

In the action defined in API, I call a command handler mediator as below :

await _mediator.Send(command, cancellationToken);

Inside the handler :

await _bus.Send(command, "endPointName", cancellationToken);

The _bus, is an instance of MassTransit. I was expecting the "Send" to throw and error after a while, how ever the call stucks indefinitely and as.net core does not return any response to user.

I changed the handler code to the below :

            var s_cts = new CancellationTokenSource();
            s_cts.CancelAfter(TimeSpan.FromSeconds(3));

            try
            {
                Task t = _bus.Send(command,"endpoint"), s_cts.Token);

                await t;
            }
            catch (Exception operationCanceledException)
            {

                throw operationCanceledException;
            }

This way, after 3 seconds of running the "Send", If I dont get an answer, it throws the exception, but still does not go through the exception middleware.

What should I change to make it happen ? Is it possible to pass the "CancellationTokenSource" instead of the default cancelationToken from asp.net core, if so, does it solve my problem ?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points
    2021-06-28T14:14:03.96+00:00

    In the asp.net middleware a cancellation error generally means the communication socket was closed, so there is no way to send a response.