【发布时间】:2021-03-09 15:38:41
【问题描述】:
所以我有一个用户架构和报价。简而言之,您需要传递一个 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一个错误,然后将您想要的任何消息或其他属性放入您抛出的错误对象中。由于这将在async函数中,因此它最终会以错误对象作为拒绝原因拒绝返回的承诺。调用者需要注意 promise 的拒绝。 -
@jfriend00 这是个好主意。你想把它作为一个答案,以便我选择最好的吗?
-
答案中包含
throw建议。
标签: javascript node.js typescript graphql