Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Last active December 9, 2020 18:05
Show Gist options
  • Save Ciantic/c771eb07ee2b69d0442ac3986fc07bd9 to your computer and use it in GitHub Desktop.
Save Ciantic/c771eb07ee2b69d0442ac3986fc07bd9 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
}));
}
}
}
}
@Ciantic
Copy link
Author

Ciantic commented Apr 21, 2016

I hereby place this to public domain.

@hidegh
Copy link

hidegh commented Oct 5, 2017

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