using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.Extensions.Options; using System; namespace Example { public class ApiExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly ObjectResultExecutor _oex; public ApiExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ObjectResultExecutor oex) { _next = next; _logger = loggerFactory.CreateLogger(); _oex = oex; } public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (Exception e) { if (context.Response.HasStarted) { _logger.LogWarning("The response has already started, the api exception middleware will not be executed"); throw; } context.Response.StatusCode = 500; context.Response.Clear(); await _oex.ExecuteAsync(new ActionContext() { HttpContext = context }, new ObjectResult(new { Error = "Exception", Exception = e })); } } } }