question

babakfakhriloo avatar image
0 Votes"
babakfakhriloo asked JerryCai-MSFT commented

Catch OperationCanceledException in Exception Middleware in asp.net core 5.0

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 ?

dotnet-aspnet-core-generaldotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

BruceBarker-8516 avatar image
0 Votes"
BruceBarker-8516 answered JerryCai-MSFT commented

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

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I do not get the exception in the middleware. I want to direct the exception so it foes to the middleware, like when there is a SQL server connection timeout issue, and it is possible to handle the exception.

0 Votes 0 ·

Hi,@babakfakhriloo Do you mean you want to catch the exception in middleware or pass exception to middleware?

0 Votes 0 ·