Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hotchocolate logging errors with a scoped service

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.

Thats what i trying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    public class CustomErrorFilter : IErrorFilter
    {
        private readonly IBaseService _service;
        private readonly IHttpContextAccessor _accessor;

        public CustomErrorFilter(IBaseService service, IHttpContextAccessor accessor)
        {
            _service = service;
            _accessor = accessor;
        }

        public IError OnError(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

>Solution :

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 OnError(IError error)
   {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var service = scope.ServiceProvider.GetRequiredService<IBaseService>(); 
            // use service
        }
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading