Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save wellingtonjhn/c18b2922b886b75ba6326e2c2a52b756 to your computer and use it in GitHub Desktop.

Select an option

Save wellingtonjhn/c18b2922b886b75ba6326e2c2a52b756 to your computer and use it in GitHub Desktop.
Built-in UseExceptionHandler extension method
public static class ExceptionHandlerExtensions
{
public static void UseGlobalExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionHandlerFeature != null)
{
var logger = loggerFactory.CreateLogger("GlobalExceptionHandler");
logger.LogError($"Unexpected error: {exceptionHandlerFeature.Error}");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var json = new
{
context.Response.StatusCode,
Message = "An error occurred whilst processing your request",
Detailed = exceptionHandlerFeature.Error
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(json));
}
});
});
}
}
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ... código omitido
app.UseGlobalExceptionHandler(loggerFactory);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment