CSHARP_CI Telegram 1505
ASP.NET Core: Глобальный обработчик исключений

Красивый и лаконичный пример реализации IExceptionHandler в .NET 8+ через switch`-выражение и сервис `IProblemDetailsService.


internal sealed class GlobalExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(exception, "Unhandled exception occurred");

httpContext.Response.StatusCode = exception switch
{
ApplicationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};

return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
Exception = exception,
ProblemDetails = new ProblemDetails
{
Type = exception.GetType().Name,
Title = "An error occured",
Detail = exception.Message
}
});
}
}

📌 Что тут важно:

- switch по типу исключения для назначения статуса ответа
- IProblemDetailsService для единообразного формирования ответа
- Логгирование всех необработанных ошибок

🔥 Такой подход делает код чище, централизует обработку ошибок и избавляет от дублирования в middleware.



tgoop.com/csharp_ci/1505
Create:
Last Update:

ASP.NET Core: Глобальный обработчик исключений

Красивый и лаконичный пример реализации IExceptionHandler в .NET 8+ через switch`-выражение и сервис `IProblemDetailsService.


internal sealed class GlobalExceptionHandler(
IProblemDetailsService problemDetailsService,
ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(exception, "Unhandled exception occurred");

httpContext.Response.StatusCode = exception switch
{
ApplicationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};

return await problemDetailsService.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
Exception = exception,
ProblemDetails = new ProblemDetails
{
Type = exception.GetType().Name,
Title = "An error occured",
Detail = exception.Message
}
});
}
}

📌 Что тут важно:

- switch по типу исключения для назначения статуса ответа
- IProblemDetailsService для единообразного формирования ответа
- Логгирование всех необработанных ошибок

🔥 Такой подход делает код чище, централизует обработку ошибок и избавляет от дублирования в middleware.

BY C# (C Sharp) programming




Share with your friend now:
tgoop.com/csharp_ci/1505

View MORE
Open in Telegram


Telegram News

Date: |

On Tuesday, some local media outlets included Sing Tao Daily cited sources as saying the Hong Kong government was considering restricting access to Telegram. Privacy Commissioner for Personal Data Ada Chung told to the Legislative Council on Monday that government officials, police and lawmakers remain the targets of “doxxing” despite a privacy law amendment last year that criminalised the malicious disclosure of personal information. Avoid compound hashtags that consist of several words. If you have a hashtag like #marketingnewsinusa, split it into smaller hashtags: “#marketing, #news, #usa. Matt Hussey, editorial director of NEAR Protocol (and former editor-in-chief of Decrypt) responded to the news of the Telegram group with “#meIRL.” “[The defendant] could not shift his criminal liability,” Hui said. best-secure-messaging-apps-shutterstock-1892950018.jpg
from us


Telegram C# (C Sharp) programming
FROM American