hotchocolate: Как вызвать множественные ошибки в массиве Errors []

Можно ли вызвать множественные ошибки в массиве Errors [], как это делает hotchocolate, когда вы пытаетесь использовать неизвестные свойства?

Если да, то как я могу это сделать?

Мой вариант использования - вернуть коллекцию ошибок при проверке объекта с помощью Validator.TryValidateObject

См. Ниже, что возвращается горячий шоколад, когда поля неизвестны. Я хочу сделать то же самое: несколько элементов в массиве Errors [].

{
  "Label": null,
  "Path": null,
  "Data": null,
  "Errors": [
    {
      "Message": "The field `date` does not exist on the type `EcritureConnection`.",
      "Code": null,
      "Path": {
        "Parent": null,
        "Depth": 0,
        "Name": "ecritures"
      },
      "Locations": [
        {
          "Line": 1,
          "Column": 75
        }
      ],
      "Extensions": {
        "type": "EcritureConnection",
        "field": "date",
        "responseName": "date",
        "specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
      },
      "Exception": null
    },
    {
      "Message": "The field `intitule` does not exist on the type `EcritureConnection`.",
      "Code": null,
      "Path": {
        "Parent": null,
        "Depth": 0,
        "Name": "ecritures"
      },
      "Locations": [
        {
          "Line": 1,
          "Column": 80
        }
      ],
      "Extensions": {
        "type": "EcritureConnection",
        "field": "intitule",
        "responseName": "intitule",
        "specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
      },
      "Exception": null
    }
  ],
  "Extensions": null,
  "ContextData": {
    "HotChocolate.Execution.ValidationErrors": true
  },
  "HasNext": null
}

person Thierry L    schedule 27.01.2021    source источник


Ответы (1)


Есть несколько способов установки ошибок в HotChocolate.

Как строить ошибки

Оба способа требуют создания объекта IError. Вы можете использовать ErrorBuilder для построения этой ошибки. Вам не нужно устанавливать все поля, но чем больше, тем лучше выглядит ошибка:

 ErrorBuilder.New()
    .SetMessage("This is the message")
    .SetCode("YOURCODE00000123")
    .SetException(ex)
    .AddLocation(context.Selection.SyntaxNode)
    .SetPath(context.Path)
    .Build()

Это приведет к возникновению такой ошибки в ответе:

{
  "errors": [
    {
      "message": "This is the message",
      "locations": [
        {
          "line": 3,
          "column": 21
        }
      ],
      "path": [
        "hello"
      ],
      "extensions": {
        "code": "YOURCODE00000123"
      }
    }
  ],
  "data": {
    "hello": "World"
  }
}

Как поднять ошибки

  1. Вы можете сообщать об ошибках в IResolverContext или IMiddlewareContext

На основе аннотаций

 public class Query
{
    public string Hello(IResolverContext context)
    {
        context.ReportError(
            ErrorBuilder.New()
                .SetMessage("This is the message")
                .SetCode("YOURCODE00000123")
                .AddLocation(context.Selection.SyntaxNode)
                .SetPath(context.Path)
                .Build());


        return "World";
    }
}

Сначала код

public class QueryType : ObjectType<Query>
{
    protected override void Configure(IObjectTypeDescriptor<Query> descriptor)
    {
        descriptor.Field(x => x.Hello)
            .Resolver(context =>
            {
                context.ReportError(
                    ErrorBuilder.New()
                        .SetMessage("This is the message")
                        .SetCode("YOURCODE00000123")
                        .AddLocation(context.Selection.SyntaxNode)
                        .SetPath(context.Path)
                        .Build());

                return "World";
            });
    }
}

  1. Бросив GraphQlException
public class Query
{
    public string Hello()
    {
        var error1 = ErrorBuilder.New()
            .SetMessage("This is the message")
            .SetCode("YOURCODE00000123")
            .Build();
        var error2 = ErrorBuilder.New()
            .SetMessage("This is the message")
            .SetCode("YOURCODE00000123")
            .Build();
        throw new GraphQLException(error1, error2)
    }
}

person Pascal Senn    schedule 28.01.2021