【问题标题】:Returning an error istead of value under a certain condition在特定条件下返回错误而不是值
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我认为这个函数值得一分为二——更易于阅读和测试。 第一个函数将检查用户是否存在,第二个函数将对用户进行操作。

    您还可以考虑为User 使用一些默认对象,即monoid。例如:

    type RawUser = {
       id: string;
       name: string;
    }
    type DefaultUser = {
       exists: boolean
    }
    
    type User = RawUser & DefaultUser;
    

    就我个人而言,我试图确保该函数始终只返回一种类型。

    老实说,在这种情况下,最好的选择是使用函数式编程范式。您可以使用 Option<T> 类型的 smth,它位于 fp-ts 库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多