Skip to content

Instantly share code, notes, and snippets.

@HamidMosalla
Created February 14, 2018 10:03
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 HamidMosalla/fc80090e8445b46ddec1ababa009750d to your computer and use it in GitHub Desktop.
Save HamidMosalla/fc80090e8445b46ddec1ababa009750d to your computer and use it in GitHub Desktop.
public static class ApiGlobalExceptionHandlerExtension
{
public static IApplicationBuilder UseWebApiExceptionHandler(this IApplicationBuilder app)
{
var loggerFactory = app.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
return app.UseExceptionHandler(HandleApiException(loggerFactory));
}
public static Action<IApplicationBuilder> HandleApiException(ILoggerFactory loggerFactory)
{
return appBuilder =>
{
appBuilder.Run(async context =>
{
var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionHandlerFeature != null)
{
var logger = loggerFactory.CreateLogger("Serilog Global exception logger");
logger.LogError(500, exceptionHandlerFeature.Error, exceptionHandlerFeature.Error.Message);
}
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An unexpected fault happened. Try again later.");
});
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment