Created
August 30, 2018 10:00
-
-
Save DonkeyKongJr/3837fb9d552e741430142b0cdea344f9 to your computer and use it in GitHub Desktop.
JsonExceptionMiddleware Handler for dotnet 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
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