gpt4 book ai didi

nestjs - 为什么 NestJS GraphQL 验证错误没有放置在错误消息字段中?

转载 作者:行者123 更新时间:2023-12-03 16:02:39 24 4
gpt4 key购买 nike

我在意外的位置看到了一些类验证器错误。我希望有一种更方便的格式来处理错误,但也许我不知道一些用于处理扩展字段中对象的 graphQL 技巧......

在运行 NestJS sample/23-graphql-code-first 时,我在 GraphQL 操场中看到以下内容:

有输入:

  addRecipe(newRecipeData: {
description: "too short"
title: "this field should fail for being too long"
ingredients: ["normal"]

}) {
title
}
}

我回来了:
  "errors": [
{
"message": "Bad Request Exception",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"addRecipe"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"response": {
"statusCode": 400,
"message": [
"title must be shorter than or equal to 30 characters",
"description must be longer than or equal to 30 characters"
],
"error": "Bad Request"
},
"status": 400,
"message": "Bad Request Exception",
"stacktrace": [
"Error: Bad Request Exception",
" at ValidationPipe.exceptionFactory nest/sample/23-graphql-code-first/node_modules/@nestjs/common/pipes/validation.pipe.js:78:20)",
...
]
}
}
}
],
"data": null
}

这些错误是深层嵌套的,“错误请求异常”没有那么有用。这是否按预期工作?

最佳答案

最佳解决方案基于 this official comment : 创建您自己的 formatError 或 formatResponse 函数。
我刚用过 in this project on GitHub它工作正常!
我的 sample :

    import { GraphQLError, GraphQLFormattedError } from 'graphql';

GraphQLModule.forRoot({
autoSchemaFile: true,
debug: false,
formatError: (error: GraphQLError) => {
const graphQLFormattedError: GraphQLFormattedError = {
message: error.extensions.exception.response.message || error.message,
};
return graphQLFormattedError;
},
}),

现在,我收到来自 GraphQL 的格式化错误响应:
{
"errors": [
{
"message": [
"firstName must be longer than or equal to 1 characters",
"lastName must be longer than or equal to 1 characters"
]
}
],
"data": null
}

关于nestjs - 为什么 NestJS GraphQL 验证错误没有放置在错误消息字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61045881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com