javascript - 在特定条件下返回错误而不是值
问题描述
所以我有一个用户模式,并提供。简而言之,您需要传递一个 usedId 来创建报价。它必须是有效的(具有此 ID 的用户需要存在于数据库中)。我想了这么多。但现在我不确定如何在解析器中正确返回错误消息/null。这是代码:
解析器:
createOffer: async (
parent: parentType, {
authorId,
},
) => {
const author = await UserModel.findById(authorId);
if (!author) {
console.log("Author doesn't exist");
// todo Add error message return
return null;
}
return OfferModel.create(
{
authorId,
},
).catch(handlePromiseError);
},
突变:
export const OfferMutations = gql`
extend type Mutation {
createOffer(
authorId: String,
): Offer!, # I want to return here Offer, or error type/null.
# I was thinking I could do || or | the ts way, but no luck.
}
`;
我该如何解决?还是我的架构/思考这个错误?
解决方案
您可以throw
出错,然后将所需的任何消息或其他属性放入Error
您抛出的对象中。当您需要将错误返回与正常返回的数据区分开来并且您可能希望在返回值中包含错误原因时,这是抛出错误的经典用法。
由于这是在一个async
函数中,它最终会以该Error
对象作为拒绝原因拒绝返回的承诺。调用者需要注意承诺拒绝。
推荐阅读
- javascript - 如何使用 ReactJs 切换元素的类
- arrays - 我得到一个未处理的运行时错误错误:渲染的钩子比上一次渲染期间更多
- javascript - Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 when connected Flask and D3.js
- apache-spark - 如何转换由 | 分隔的顺序数据 并且在 pyspark 中的行和列中没有换行符
- javascript - 在 React 中状态更改后,功能组件不会重新渲染
- java - 无法更改 HTTP 接受标头 - 对包含“lang”的多部分 FormData 使用不同的区域设置解析策略
- python - 如何从具有范围的数据库中获取数据?
- php - 带有自定义分类法的 Wordpress 自定义查询 - 分页错误
- c# - 具有多种命令类型的命令行解析器
- javascript - 从文本文件中读取多行,然后通过将读取的文件插入到函数上来迭代函数