ultimate/Ultimate/Extensions/ExceptionMiddlewareExtensions.cs
2023-06-12 10:26:01 +02:00

64 lines
No EOL
2.6 KiB
C#

// ***********************************************************************
// Assembly : Ultimate
// Author : frede
// Created : 2023 06 11 14:22
//
// Last Modified By : frede
// Last Modified On : 2023 06 11 14:22
// ***********************************************************************
// <copyright file="ExceptionMiddlewareExtensions.cs" company="FCS">
// Copyright (C) 2023-2023 FCS Frede's Computer Services.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see [https://www.gnu.org/licenses]
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Net;
using Contracts;
using Entities.ErrorModel;
using Entities.Exceptions;
using Microsoft.AspNetCore.Diagnostics;
namespace Ultimate.Extensions;
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureExceptionHandler(this WebApplication app, ILoggerManager logger)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature != null)
{
context.Response.StatusCode = contextFeature.Error switch
{
NotFoundException => StatusCodes.Status404NotFound,
_ => StatusCodes.Status500InternalServerError
};
logger.LogError($"Exception occurred: {contextFeature.Error}");
await context.Response.WriteAsync(new ErrorDetails
{
StatusCode = context.Response.StatusCode,
Message = contextFeature.Error.Message
}.ToString());
}
});
});
}
}