Last active
March 3, 2024 04:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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