Last active
December 9, 2020 18:05
-
-
Save Ciantic/c771eb07ee2b69d0442ac3986fc07bd9 to your computer and use it in GitHub Desktop.
Exception Middleware vs Exception Filter both return ObjectResult, ASP.NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.AspNetCore.Mvc.Filters; | |
namespace Example | |
{ | |
public class ApiExceptionFilter : Attribute, IExceptionFilter | |
{ | |
public void OnException(ExceptionContext context) | |
{ | |
if (context.Exception is Exception) { | |
context.Result = new ObjectResult(new { | |
Error = "Exception", | |
Exception = context.Exception | |
}); | |
context.Exception = null; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<ApiExceptionMiddleware>(); | |
_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 | |
})); | |
} | |
} | |
} | |
} |
This is true, but a 404 error will be catched by the middleware only ;)
Also if you have an ex. filter and if it kicks in, then the middleware won't be executed anymore...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hereby place this to public domain.