Catch OperationCanceledException in Exception Middleware in core 5.0

babak fakhriloo 41 Reputation points

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;

                await _requestDelegate(httpContext);
            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 core does not return any response to user.

I changed the handler code to the below :

            var s_cts = new CancellationTokenSource();

                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 core, if so, does it solve my problem ?

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

1 answer

Sort by: Most helpful
  1. Bruce Barker 801 Reputation points

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