Skip to content

Instantly share code, notes, and snippets.

@DonkeyKongJr
Created August 30, 2018 10:00
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 DonkeyKongJr/3837fb9d552e741430142b0cdea344f9 to your computer and use it in GitHub Desktop.
Save DonkeyKongJr/3837fb9d552e741430142b0cdea344f9 to your computer and use it in GitHub Desktop.
JsonExceptionMiddleware Handler for dotnet core
namespace MyApp.Services.Handler
{
public class JsonExceptionMiddleware
{
private readonly IHostingEnvironment _environment;
private const string DefaultErrorMessage = "A server error occurred.";
public JsonExceptionMiddleware(IHostingEnvironment environment)
{
_environment = environment;
}
public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var ex = httpContext.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex == null)
{
return;
}
var error = new ApiError();
if (_environment.IsDevelopment())
{
error.Message = ex.Message;
error.Detail = ex.StackTrace;
error.InnerException = ex.InnerException != null ? ex.InnerException.Message : string.Empty;
}
else
{
error.Message = DefaultErrorMessage;
error.Detail = ex.Message;
}
httpContext.Response.ContentType = "application/json";
using (var writer = new StreamWriter(httpContext.Response.Body))
{
new JsonSerializer().Serialize(writer, error);
await writer.FlushAsync().ConfigureAwait(false);
}
}
}
public static class JsonExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseJsonExceptionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<JsonExceptionMiddleware>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment