【问题标题】:Proper error handling when connecting to Mailchimp api连接到 Mailchimp api 时的正确错误处理
【发布时间】:2021-08-29 08:54:13
【问题描述】:

相对较新的节点。我正在构建一个基本的应用程序,通过使用MailChimp's API 将用户注册到电子邮件通讯。要在我的 Mailchimp 帐户上订阅用户,我有以下 POST 路由 uses their Node library

/*** POST route endpoint ***/
app.post("/", (req, res) => {
  console.log("Serving a POST request at root route.");

  // Define data member based on parameters of req
  // and global constants.
  const member = {
      email_address: req.body.email,
      email_type: EMAIL_TYPE,
      status: SUBSCRIPTION_STATUS,
      language: LANGUAGE,
      vip: VIP,
      merge_fields: {
        FNAME: req.body.firstName,
        LNAME: req.body.lastName
      }
  };

  mailchimpClient.setConfig({
    apiKey: MAILCHIMP_API_KEY,
    server: SERVER,
  });

  // Define async function that makes a call to the mailchimp batch POST lists/{list_id} endpoint.
  const postIt = async () => {
    const response = await mailchimpClient.lists.batchListMembers(MAILCHIMP_LIST_ID, {
      members: [member],
      update_existing: false
    });
    console.log(JSON.stringify(response));  // Want to read some output in terminal
  };

  // Call the async function you defined
  postIt()
      .then(()=>res.send("<h1>All good, thanks!</h1>"))
      .catch(()=>res.send("<h1>Error!</h1>"));
});

为了测试代码是否正确响应错误,我添加了以下虚构用户两次:

第一次,服务器和终端上的一切都按预期成功。服务器:

和终端输出:

当用户自己看到&lt;h1&gt;,上面写着“一切都好,谢谢!”:

但是我第二次输入 Jane Doe 的信息,而 Mailchimp 显然确实给了我预期的错误(因为 update_existingpostIt() 的定义中是 false),我在 catch() 中的失败回调是 调用,用户仍会在浏览器中看到成功消息!

所以我们这里有一个旨在失败的 POST 调用,但似乎我可能没有很好地使用 postIt() 返回的 Promise。关于我做错了什么有什么想法吗?

【问题讨论】:

    标签: node.js express error-handling promise mailchimp-api-v3.0


    【解决方案1】:

    看起来 mailchimp 客户端不会抛出要捕获的异常。

    请注意,即使在 mailchimp 客户端“失败”时,您的第二个控制台日志也会执行,因此没有什么可捕获的。它似乎只是在响应中填充了一个“错误”键。许多 API 以自己的方式执行此操作。有些 API 具有“状态”字段等。

    如果您想在您的 Promise 捕获处理程序中捕获此错误,您必须通过解析该 mailchimp 响应并自己引发异常来检测异步函数中的失败场景。

     const postIt = async () => {
        const response = await mailchimpClient.lists.batchListMembers(MAILCHIMP_LIST_ID, {
          members: [member],
          update_existing: false
        });
        if (response.errors.length) { 
             throw new Error(response.errors);
        }
      };
      postIt().catch(errors => console.log(errors));
    

    【讨论】:

    • 啊,是的,在发布此消息几分钟后,我对自己说,console.log() 的确切行使得postIt() 实际上永远不会抛出任何不好的东西。 mailchimp 调用从不抛出任何东西,所以一切都很好。我有时很难理解 API 调用是否会抛出错误或填充 JSON 有效负载,我必须弄清楚。感谢您的回复,我接受了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2019-07-30
    • 2018-12-06
    • 1970-01-01
    • 2019-08-08
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多