Last active
March 2, 2025 13:40
-
-
Save davepcallan/18ab94f97bc0dd0f005824386f7b03ee to your computer and use it in GitHub Desktop.
ASP.NET 8 Global exception handling with IExceptionHandler example
This file contains hidden or 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; | |
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