问题描述
Node.js 相对较新。我正在构建一个基本的应用程序,通过使用 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>"));
});
第一次,服务器和终端都按预期成功。服务器:
和终端输出:
而用户自己会看到<h1>
,上面写着“一切都好,谢谢!”:
但是我第二次输入 Jane Doe 的信息时,Mailchimp 显然确实给了我预期的错误(因为 update_existing
在 false
的定义中是 postIt()
),我的失败回调在catch()
被未调用,并且用户的浏览器中仍会收到一条成功消息!
所以我们这里有一个旨在失败的 POST 调用,但似乎我可能没有很好地使用 Promise
返回的 postIt()
。对我做错了什么有任何想法吗?
解决方法
看起来 mailchimp 客户端不会抛出异常来捕获。
请注意,即使 mailchimp 客户端“失败”,您的第二个控制台日志也是如何执行的,因此没有什么可捕获的。它似乎只是在响应中填充“错误”键。许多 API 以自己的方式执行此操作。有些 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));