【问题标题】:How can I get more error details or logging, when an exception is thrown in a HotChocolate GraphQL server?当 HotChocolate GraphQL 服务器中引发异常时,如何获取更多错误详细信息或日志记录?
【发布时间】:2021-01-17 18:19:09
【问题描述】:

我正在构建一个简单的 HotChocolate GraphQl 服务器,HotChocolate 会抛出一个 Unexpected Execution Error,但不会公开任何有关错误的信息,只要我发布一个针对它的请求。 我如何向后端(BananaCakePop、Postman、Insomnia 等)发布请求并不重要。
响应如下所示:

{
  "errors": [
    {
      "message": "Unexpected Execution Error",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "pong"
      ]
    }
  ],
  "data": {
    "pong": null
  }
}

请求响应不包含更多信息,并且没有任何内容记录到应用程序控制台。 尝试找出问题所在的合理下一步是什么?

【问题讨论】:

    标签: c# asp.net-core graphql hotchocolate


    【解决方案1】:

    默认情况下,如果没有附加调试器,HotChocolate 不会公开异常的详细信息。 因此,要获取您的错误消息,您可以:

    • 将调试器附加到您的服务器,然后它将在请求中公开异常详细信息(也就是在调试中启动您的服务器:D)
    • 以更适合您的开发风格的方式更改此行为。

    这是在 V11 或 V12 中更改默认行为的方法:

    public class Startup
    {
        private readonly IWebHostEnvironment _env;
    
        public Startup(IWebHostEnvironment env)
        {
            _env = env;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddGraphQLServer()
                ...
                // You can change _env.IsDevelopment() to whatever condition you want.
                // If the condition evaluates to true, the server will expose it's exceptions details
                // within the reponse.
                .ModifyRequestOptions(opt => opt.IncludeExceptionDetails = _env.IsDevelopment());  
        }
    }
    

    这是在 V10 中更改默认行为的方法:

    public class Startup
    {
        private readonly IWebHostEnvironment _env;
    
        public Startup(IWebHostEnvironment env)
        {
            _env = env;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGraphQL(
                Schema.Create(builder =>
                {
                    ...
                }),
                // You can change _env.IsDevelopment() to whatever condition you want.
                // If the condition evaluates to true, the server will expose it's exceptions details
                // within the reponse.
                new QueryExecutionOptions {IncludeExceptionDetails = _env.IsDevelopment()}
            );
        }
    }
    

    您还可以向您的应用程序添加一个 IErrorFilter,例如,可以将您的异常记录到您的语言环境控制台,或将异常转换为 GraphQlErrors。 有关此主题的更多信息,请查看:

    【讨论】:

    • 你说的完全是错误的。请查收:stackoverflow.com/help/self-answer
    • 不会改变我所说的。我们鼓励您回答自己的问题,但这些问题需要也是有效的。请阅读How to Ask
    • @JayChase 这就是答案所说的(除了 IsDev 而不是 true)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多