Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Last active March 2, 2025 13:40
Show Gist options
  • Save davepcallan/18ab94f97bc0dd0f005824386f7b03ee to your computer and use it in GitHub Desktop.
Save davepcallan/18ab94f97bc0dd0f005824386f7b03ee to your computer and use it in GitHub Desktop.
ASP.NET 8 Global exception handling with IExceptionHandler example
using Microsoft.AspNetCore.Diagnostics;
namespace Samples;
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var exceptionMessage = exception.Message;
logger.LogError(
"Error Message: {exceptionMessage}, Time of occurrence {time}",
exceptionMessage, DateTime.UtcNow);
// Return false to continue with the default behavior
// - or - return true to signal that this exception is handled
return ValueTask.FromResult(false);
}
}
//Program.cs
//builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
//app.UseExceptionHandler("/Error");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment