59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
namespace Webzine.WebApplication.Filters;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
/// <summary>
|
|
/// Filtre d'exception global qui intercepte toute exception non geree et la journalise automatiquement.
|
|
/// </summary>
|
|
public class GlobalExceptionFilter : IExceptionFilter
|
|
{
|
|
private readonly ILogger<GlobalExceptionFilter> logger;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="GlobalExceptionFilter"/> class.
|
|
/// </summary>
|
|
/// <param name="logger">Service de journalisation injecte.</param>
|
|
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
|
|
{
|
|
this.logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public void OnException(ExceptionContext context)
|
|
{
|
|
string detail = BuildExceptionDetail(context.Exception);
|
|
|
|
this.logger.LogError(
|
|
context.Exception,
|
|
"Erreur non geree dans {Action} : {Message} | Details: {Details}",
|
|
context.ActionDescriptor.DisplayName,
|
|
context.Exception.Message,
|
|
detail);
|
|
|
|
context.Result = new ObjectResult(new
|
|
{
|
|
erreur = "Une erreur inattendue est survenue.",
|
|
detail = context.Exception.Message,
|
|
})
|
|
{
|
|
StatusCode = StatusCodes.Status500InternalServerError,
|
|
};
|
|
|
|
context.ExceptionHandled = true;
|
|
}
|
|
|
|
private static string BuildExceptionDetail(Exception exception)
|
|
{
|
|
var messages = new List<string>();
|
|
Exception? current = exception;
|
|
|
|
while (current != null)
|
|
{
|
|
messages.Add($"{current.GetType().Name}: {current.Message}");
|
|
current = current.InnerException;
|
|
}
|
|
|
|
return string.Join(" --> ", messages);
|
|
}
|
|
} |