首页 > 解决方案 > 在特定条件下返回错误而不是值

问题描述

所以我有一个用户模式,并提供。简而言之,您需要传递一个 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.
    }
`;

我该如何解决?还是我的架构/思考这个错误?

标签: javascriptnode.jstypescriptgraphql

解决方案


您可以throw出错,然后将所需的任何消息或其他属性放入Error您抛出的对象中。当您需要将错误返回与正常返回的数据区分开来并且您可能希望在返回值中包含错误原因时,这是抛出错误的经典用法。

由于这是在一个async函数中,它最终会以该Error对象作为拒绝原因拒绝返回的承诺。调用者需要注意承诺拒绝。


推荐阅读