Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

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

Select an option

Save wellingtonjhn/fe1d2791b8aa358e11f6a785388b7777 to your computer and use it in GitHub Desktop.
Problem Details Exception Handler
public static class ProblemDetailsExtensions
{
public static void UseProblemDetailsExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionHandlerFeature != null)
{
var exception = exceptionHandlerFeature.Error;
var problemDetails = new ProblemDetails
{
Instance = context.Request.HttpContext.Request.Path
};
if (exception is BadHttpRequestException badHttpRequestException)
{
problemDetails.Title = "The request is invalid";
problemDetails.Status = StatusCodes.Status400BadRequest;
problemDetails.Detail = badHttpRequestException.Message;
}
else
{
var logger = loggerFactory.CreateLogger("GlobalExceptionHandler");
logger.LogError($"Unexpected error: {exceptionHandlerFeature.Error}");
problemDetails.Title = exception.Message;
problemDetails.Status = StatusCodes.Status500InternalServerError;
problemDetails.Detail = exception.Demystify().ToString();
}
context.Response.StatusCode = problemDetails.Status.Value;
context.Response.ContentType = "application/problem+json";
var json = JsonConvert.SerializeObject(problemDetails, SerializerSettings.JsonSerializerSettings);
await context.Response.WriteAsync(json);
}
});
});
}
}
public class Startup
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// ... código omitido
app.UseProblemDetailsExceptionHandler(loggerFactory);
app.UseMvc();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment