jtr/Jtr.Tools.API/GlobalExceptionHandler.cs
mdnapo 96c203f842
All checks were successful
Run the JSON parser tests / test (push) Has been skipped
Moved UI to separate project, added Dockerfile & renamed project
2024-10-19 12:04:40 +02:00

46 lines
1.3 KiB
C#

using Jtr.Parsing;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace Jtr.Tools.API;
public class GlobalExceptionHandler : IExceptionHandler
{
public const int ParsingExceptionStatusCode = 499;
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken
)
{
switch (exception)
{
case SyntaxException:
_logger.LogError(exception, "An exception occurred: {Message}", exception.Message);
var problem = new ProblemDetails
{
Status = ParsingExceptionStatusCode,
Title = "Parsing Exception",
Detail = exception.Message
};
httpContext.Response.StatusCode = problem.Status.Value;
await httpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
return true;
default:
return false;
}
}
}