Skip to content

Instantly share code, notes, and snippets.

@ccpu
Forked from Ciantic/ExceptionFilter.cs
Created December 9, 2020 18:05
Show Gist options
  • Save ccpu/064b1e3e3fd93f67fabcf8d99eec69ef to your computer and use it in GitHub Desktop.
Save ccpu/064b1e3e3fd93f67fabcf8d99eec69ef to your computer and use it in GitHub Desktop.
Exception Middleware vs Exception Filter both return ObjectResult, ASP.NET Core
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;
}
}
}
}
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