-
-
Save ccpu/064b1e3e3fd93f67fabcf8d99eec69ef 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 | |
})); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment