Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

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

Select an option

Save wellingtonjhn/39f5391a5dcf0cf3e7087765b9a806c1 to your computer and use it in GitHub Desktop.
Custom Global Exception Handler MIddleware
public class GlobalExceptionHandlerMiddleware : IMiddleware
{
private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger;
public GlobalExceptionHandlerMiddleware(ILogger<GlobalExceptionHandlerMiddleware> logger)
{
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
_logger.LogError($"Unexpected error: {ex}");
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var json = new
{
context.Response.StatusCode,
Message = "An error occurred whilst processing your request",
Detailed = exception
};
return context.Response.WriteAsync(JsonConvert.SerializeObject(json));
}
}
public static class GlobalExceptionHandlerMiddlewareExtensions
{
public static IServiceCollection AddGlobalExceptionHandlerMiddleware(this IServiceCollection services)
{
return services.AddTransient<GlobalExceptionHandlerMiddleware>();
}
public static void UseGlobalExceptionHandlerMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ... código omitido
services.AddGlobalExceptionHandlerMiddleware();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ... código omitido
app.UseGlobalExceptionHandlerMiddleware();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment