问题描述
是否有可能在 Errors[] 数组中引发多个错误,就像 hotchocolate 在您尝试使用未知属性时所做的那样?
如果是,我该怎么做?
我的用例是在使用 Validator.TryValidateObject 验证对象时返回错误集合
看看下面当字段未知时 hotchocolate 返回什么。 我想做同样的事情: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`.","Column": 80
}
],"field": "intitule","responseName": "intitule","Exception": null
}
],"Extensions": null,"ContextData": {
"HotChocolate.Execution.ValidationErrors": true
},"HasNext": null
}
解决方法
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"
}
}
如何引发错误
- 您可以在
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";
});
}
}
- 通过抛出
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)
}
}