I have a controller in ASP.NET that will be making a handful of api calls.
public async Task<IActionResult> PostRequest([FromBody] RequestModel request)
{
var firstApiCall = await _service.MakeFirstApiCall( ... );
var secondApiCall = await _service.MakeSecondApiCall( ... );
return new OkObjectResult(new { });
}
I need middleware to handle exceptions globally (shown below).
After firstApiCall throws an error, the exceptionMiddleware catches it, but then continues to return new OkObjectResult(new { }); instead of the next line, secondApiCall
The middleware is shown below. This is the complete vanilla version, I just want to see it continue to the next line rather then go to the return statement.
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<ApiExceptionMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
}
}
}
If I wrap a try/catch around firstApiCall, it continues to the next line fine. Unsure why the behaviour isn't the same through the middleware.
return new OkObjectResult(new { });of your action is ever called on exception, thats not how exceptions work. Its probably our middleware which returns it? Also don't abuse exceptions for flow control. Last but not least, you can start both task without awaiting them directly but wait for both:await Task.WhenAll(task1, task2)this way your second call can be called w/o awaiting the response of the first one (assuming it doesnt depend on a value returned from the first one)