You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HotChocolate 12.5.2中如何在作用域服务中拦截并记录错误

HotChocolate 12.5.2 错误拦截相关问题

我当前使用HotChocolate 12.5.2,想要找到拦截错误的最佳位置。查阅官方文档后了解到,IErrorFilter接口的OnError方法会在每次错误发生时触发,但该接口的实现是单例模式。我有以下几个疑问:

  • 是否存在作用域服务级别的错误拦截点?
  • 如果继续使用IErrorFilter,如何在其中注入作用域服务(比如我自定义的IBaseService——一个用于访问应用DbContext的泛型作用域服务)来记录错误?
  • 使用IErrorFilter是否是拦截和记录错误的最佳实践?

以下是我尝试实现的代码:

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;
    }
}

内容的提问来源于stack exchange,提问作者Humberto Filho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:35:13