So I'm trying to log errors with HotChocolate 12.5.2
and I want to know the best place to intercept the errors. Reading the hotchocolate Documentation I found that the interface IErrorFilter
have a OnError
method that is called every time an error occurs, but its implementation is singleton. Is there somewhere where the service is scoped that I can intercept this error, or is there a way to inject my Scoped service in a to log the error?
I can intercept and personalize my error but I cant inject my service. I just want to know if this is the best place to intercept the error and if is the best pratice to log errors here.
This is what I'm trying:
public class CustomErrorFilter : IErrorFilter
{
private readonly IBaseService _service;
private readonly IHttpContextAccessor _accessor;
public CustomErrorFilter(IBaseService service, IHttpContextAccessor accessor)
{
_service = service;
_accessor = accessor;
}
public IError one rror(IError error)
{
if (error.Exception is not null)
return error.WithMessage(error.Exception.Message);
_service.Add<Log, LogViewModel>(new LogViewModel()
{
Message= error.Message,
}, _accessor.HttpContext.User);
return error;
}
}
IBaseService
is my generic class that access my application DbContext
and is a Scoped service
CodePudding user response:
Try injecting IServiceScopeFactory
instead your scoped dependency and create scope and resolve dependency in OnError
handler:
public class CustomErrorFilter : IErrorFilter
{
private readonly IServiceScopeFactory _scopeFactory;
//...
public CustomErrorFilter(IServiceScopeFactory scopeFactory, IHttpContextAccessor accessor)
{
_scopeFactory = scopeFactory;
_accessor = accessor;
}
public IError one rror(IError error)
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IBaseService>();
// use service
}
}
}