Skip to content

Commit

Permalink
Add global exception handler (#421)
Browse files Browse the repository at this point in the history
  • Loading branch information
idormenco authored Oct 14, 2023
1 parent c7b57be commit 2b6a72a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
59 changes: 59 additions & 0 deletions src/api/VoteMonitor.Api/Extensions/ExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using System;
using System.Net;

namespace VoteMonitor.Api.Extensions;

/// <summary>
/// extensions for global exception handling
/// </summary>
public static class ExceptionHandlerExtensions
{
/// <summary>
/// registers the default global exception handler which will log the exceptions on the server and return a user-friendly json response to the client when unhandled exceptions occur.
/// TIP: when using this exception handler, you may want to turn off the asp.net core exception middleware logging to avoid duplication like so:
/// <code>
/// "Logging": { "LogLevel": { "Default": "Warning", "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware": "None" } }
/// </code>
/// </summary>
public static IApplicationBuilder UseDefaultExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(errApp =>
{
errApp.Run(async ctx =>
{
var exHandlerFeature = ctx.Features.Get<IExceptionHandlerFeature>();
if (exHandlerFeature is not null)
{

var http = exHandlerFeature.Endpoint?.DisplayName?.Split(" => ")[0];
var type = exHandlerFeature.Error.GetType().Name;
var error = exHandlerFeature.Error.Message;
var msg =
$@"=================================
{http}
TYPE: {type}
REASON: {error}
---------------------------------
{exHandlerFeature.Error.StackTrace}";

Log.Error("{@http}{@type}{@reason}{@exception}", http, type, error, exHandlerFeature.Error);

ctx.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
ctx.Response.ContentType = "application/problem+json";
await ctx.Response.WriteAsJsonAsync(new ProblemDetails
{
Title = "An error occurred",
Detail = error,
Type = type,
Status = (int)HttpStatusCode.BadRequest
});
}
});
});

return app;
}
}
4 changes: 2 additions & 2 deletions src/api/VoteMonitor.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@
.AllowAnyHeader();
}));


var app = builder.Build();
app.UseDefaultExceptionHandler();
app.UseSerilogRequestLogging();

app.UseStaticFiles();
if (builder.Environment.IsDevelopment())
{
Expand All @@ -58,7 +59,6 @@

app.UseSwaggerAndUi();
app.UseCors(CorsPolicyName);

app.MapControllers();
app.MapHealthChecks("/health", new HealthCheckOptions
{
Expand Down

0 comments on commit 2b6a72a

Please sign in to comment.