60 lines
1.3 KiB
C#
60 lines
1.3 KiB
C#
|
|
namespace Diary.Shared
|
|
{
|
|
public partial class ExceptionHandlingMiddleware : IMiddleware
|
|
{
|
|
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
|
|
|
|
public ExceptionHandlingMiddleware(ILogger<ExceptionHandlingMiddleware> logger)
|
|
{
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
|
{
|
|
try
|
|
{
|
|
await next(context);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
_logger.LogError(e, "Error received from ExceptionHandlingMiddleware");
|
|
await HandleExceptionAsync(context, e);
|
|
}
|
|
}
|
|
|
|
private static async Task HandleExceptionAsync(HttpContext httpContext, Exception exception)
|
|
{
|
|
ExceptionDetails exceptionDetails;
|
|
httpContext.Response.ContentType = "application/json";
|
|
|
|
if (exception.InnerException is AppException)
|
|
{
|
|
exception = exception.InnerException;
|
|
}
|
|
|
|
if (exception is AppException applicationException)
|
|
{
|
|
httpContext.Response.StatusCode = (int)applicationException.StatusCode;
|
|
|
|
exceptionDetails = new()
|
|
{
|
|
Message = applicationException.Message,
|
|
Title = applicationException.Title
|
|
};
|
|
}
|
|
else
|
|
{
|
|
httpContext.Response.StatusCode = 500;
|
|
|
|
exceptionDetails = new()
|
|
{
|
|
Message = exception.Message,
|
|
Title = "API Error"
|
|
};
|
|
}
|
|
|
|
await httpContext.Response.WriteAsync(exceptionDetails.ToString());
|
|
}
|
|
}
|
|
} |