连接到 Mailchimp 时的正确错误处理 api

Proper error handling when connecting to Mailchimp api

Node.js 相对较新。我正在构建一个基本的应用程序,通过使用 MailChimp's API. To subscribe users on my Mailchimp account, I have the following POST route which 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>"));
});

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

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

和终端输出:

而用户自己看到的是 <h1>,上面写着“很好,谢谢!”:

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

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

不像 mailchimp 客户端抛出要捕获的异常。

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

如果您想在 promise catch 处理程序中捕获此错误,则必须通过解析 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));