Skip to content

Commit

Permalink
Update with new exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
shawnwildermuth committed Jan 21, 2024
1 parent 8a08b88 commit 91b71dc
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

svcs.AddDbContext<BillingContext>();

svcs.AddExceptionHandler<RestDesignExceptionHandler>();

svcs.AddHttpCacheHeaders();

svcs.AddCors(setup =>
Expand Down Expand Up @@ -72,6 +74,9 @@

var app = builder.Build();

// Using empty configuration to force it to use IExceptionHandler
app.UseExceptionHandler(_ => { });

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down
57 changes: 57 additions & 0 deletions src/Services/RestDesignExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System.Text.Json;
using System.Threading;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace RestDesign.Services;

public class RestDesignExceptionHandler : IExceptionHandler
{
private readonly IHostEnvironment _environment;

public RestDesignExceptionHandler(IHostEnvironment environment)
{
_environment = environment;
}

public async ValueTask<bool> TryHandleAsync(HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is not null)
{
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/json";

// Generate the response
object? error;

if (_environment.IsProduction())
{
error = new
{
Message = "Server Error. Please contact support.",
MessageKey = "exceptionThrownServer"
};
}
else
{
error = new
{
Message = exception.Message,
MessageKey = "",
StackTrace = exception.StackTrace,
ExceptionType = exception.GetType().Name,
InnerException = exception.InnerException?.ToString()
};
}

await httpContext.Response.WriteAsJsonAsync(error);

return true;
}

return false;
}
}

0 comments on commit 91b71dc

Please sign in to comment.