Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add global exception handler #421

Merged
merged 1 commit into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading