Hi,
I'm trying to do global handling in a .NET Core 7 project. However, when I import the IExceptionHandler interface, using System.Web.Http.ExceptionHandling adds this class. There is a method to this too. But later, when I try to add it to program.cs, it does not see this class. What is the problem here? Also can you make an example? Can you help me.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Web.Http.ExceptionHandling;
namespace FlightProject.Application.Exceptions
{
public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
string errorMessage = $"Bir hata oluştu. Hata mesajı : {exception.Message}";
_logger.LogError(exception, errorMessage);
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(new
{
Title = "Server Error",
Status = httpContext.Response.StatusCode,
Message = errorMessage
});
return true;
}
}
}
Program.cs
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();