Skip to content

Instantly share code, notes, and snippets.

@DejanMilicic
Last active March 15, 2018 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DejanMilicic/b1cbf823ea99811102a6d4323804a554 to your computer and use it in GitHub Desktop.
Save DejanMilicic/b1cbf823ea99811102a6d4323804a554 to your computer and use it in GitHub Desktop.
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Infrastructure.Middleware
{
public class MediatrErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public MediatrErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other scoped dependencies */)
{
try
{
// must be awaited
await next(context);
}
catch (Exception ex)
{
if (ShouldHandleException(ex))
{
await HandleExceptionAsync(context, ex);
}
else
{
throw;
}
}
}
private static bool ShouldHandleException(Exception exception)
{
if (exception is MediatrUnauthorizedAccessException) return true;
if (exception is MediatrValidationException) return true;
if (exception is AggregateException)
{
return (exception as AggregateException).Flatten().InnerExceptions
.Any(x => x is MediatrUnauthorizedAccessException || x is MediatrValidationException);
}
return false;
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
Exception e;
if (exception is AggregateException)
{
e = (exception as AggregateException).Flatten().InnerExceptions.FirstOrDefault();
}
else
{
e = exception;
}
if (e is MediatrUnauthorizedAccessException)
{
var error = new
{
message = e.Message,
exception = e.GetType().Name
};
return WriteExceptionAsync(context, HttpStatusCode.Unauthorized, error);
}
else if (e is MediatrValidationException)
{
MediatrValidationException mve = e as MediatrValidationException;
string message = "<span>Validation failed</span>" + "<ul>" + string.Join("", mve.Errors.Select(x => "<li>" + x.ErrorMessage.ToString() + "</li>")) + "</ul>";
var fields = mve.Errors.Select(x => x.PropertyName);
var error = new
{
message = message,
fields = fields,
exception = e.GetType().Name
};
return WriteExceptionAsync(context, HttpStatusCode.BadRequest, error);
}
return Task.FromResult(0);
}
private static Task WriteExceptionAsync(HttpContext context, HttpStatusCode code, object error)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)code;
return response.WriteAsync(JsonConvert.SerializeObject(error));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment