Global Exception Handling in NET : Implementing IExceptionHandler

Listen to this Post

Whether you use the result pattern or not, exceptions can occur. The solution for handling exceptions is to create a global exception handler that catches and manages all unexpected exceptions. Before .NET 8, you could implement a global exception handler using middleware. From .NET 8, it’s even easier to create a global exception handler by utilizing the IExceptionHandler interface.

Interestingly, you can add multiple IExceptionHandler implementations and they will be called in the order in which they are registered. By using AddProblemDetails, you can configure Problem Details in HTTP responses in a standardized way.

Source: https://nikolatech.net
Code Example: https://www.nikolatech.net/codes/global-exception-handler-example

You Should Know:

Here are practical implementations and related commands for exception handling:

1. Basic .NET 8 Global Exception Handler Implementation

public class GlobalExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
= "Server error",
Detail = exception.Message
};

httpContext.Response.StatusCode = problemDetails.Status.Value;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}
}

2. Registering Multiple Handlers in Program.cs

builder.Services.AddExceptionHandler<CustomExceptionHandler>();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();

3. Linux Commands for Monitoring .NET Exceptions

 Monitor .NET application logs
journalctl -u yourdotnetapp.service --since "1 hour ago" | grep -i exception

Check for unhandled exceptions in systemd logs
sudo journalctl -xe | grep -A 10 -B 10 "UnhandledException"

Analyze memory dump after crash
dotnet-dump collect -p <PID> && dotnet-dump analyze <dumpfile>

4. Windows Commands for Exception Handling

 Check Event Viewer for .NET exceptions
Get-WinEvent -LogName "Application" | Where-Object {$_.Message -like "Exception"}

Monitor IIS for unhandled exceptions
Get-EventLog -LogName Application -Source "ASP.NET 8.0.0" -After (Get-Date).AddHours(-1)

5. Advanced Problem Details Configuration

builder.Services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = ctx =>
{
ctx.ProblemDetails.Extensions.Add("timestamp", DateTime.UtcNow);
ctx.ProblemDetails.Extensions.Add("instance", ctx.HttpContext.Request.Path);
};
});

6. Testing Exception Handling with curl

 Test your exception handler
curl -i -H "Accept: application/json" https://your-api.com/error-endpoint

Check problem details response
curl -s https://your-api.com/error-endpoint | jq .

7. Logging Exceptions to File in Linux

 Configure logging in appsettings.json
{
"Logging": {
"File": {
"Path": "/var/log/dotnet/exceptions.log",
"Append": true,
"MinLevel": "Warning"
}
}
}

What Undercode Say:

Exception handling is critical in production applications, and .NET 8’s IExceptionHandler provides a clean, modular approach. The integration with Problem Details (RFC 7807) standardizes error responses, making APIs more consistent and client-friendly.

For system administrators, monitoring these exceptions is crucial. On Linux systems, journalctl becomes your best friend for tracking .NET application crashes. Windows administrators should leverage PowerShell to query event logs efficiently.

Developers should implement multiple exception handlers for different scenarios (validation errors, database exceptions, etc.) and test them thoroughly using tools like curl or Postman. Remember to log sufficient context with each exception while being mindful of sensitive data.

The true power comes from combining this with proper monitoring:

 Set up log rotation for exception logs
sudo nano /etc/logrotate.d/dotnet-exceptions
 Windows scheduled task to email critical exceptions
Register-ScheduledJob -Name "DailyExceptionReport" -ScriptBlock {
Get-EventLog -LogName Application -EntryType Error -After (Get-Date).AddDays(-1) |
Where-Object {$_.Source -like "ASP.NET"} |
Send-MailMessage -From [email protected] -To [email protected]
} -Trigger (New-JobTrigger -Daily -At "8:00 AM")

Expected Output:

A well-structured error response with Problem Details format:

{
"type": "https://tools.ietf.org/html/rfc7231section-6.6.1",
"title": "Internal Server Error",
"status": 500,
"detail": "Database connection failed",
"instance": "/api/users",
"timestamp": "2023-11-15T14:22:45.123Z",
"traceId": "00-abcdef1234567890abcdef1234567890-abcdef1234567890-00"
}

References:

Reported By: Nikola Knez – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image