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