Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Last active March 3, 2024 04:55
Show Gist options
  • Save davepcallan/f8724a98db78f1ccfda5c04fad9a9efc to your computer and use it in GitHub Desktop.
Save davepcallan/f8724a98db78f1ccfda5c04fad9a9efc to your computer and use it in GitHub Desktop.
Example of using .NET 8 IExceptionHandler to return 7807 ProblemDetails compliant response to client
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using System.Net;
namespace Samples;
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var exceptionMessage = exception.Message;
logger.LogError(exception,
"Error Message: {exceptionMessage}, Time of occurrence {time}",
exceptionMessage, DateTime.UtcNow);
// Return RFC 7807 - compliant payload to the client
httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await httpContext.Response.WriteAsJsonAsync(new ProblemDetails
{
Title = "An error occurred",
Detail = exception.Message,
Type = exception.GetType().Name,
Status = (int)HttpStatusCode.BadRequest
}, cancellationToken: cancellationToken);
// Return false to continue with the default behavior
// - or - return true to signal that this exception is handled
return true;
}
}
//Program.cs ...
//var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddProblemDetails();
//var app = builder.Build();
//app.UseStatusCodePages();
//app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment