在 Firebase 中执行邮件枪云功能时获取"TypeError: Cannot read property 'catch' of undefined"



我正在尝试使用MailGun和Firebase Cloud功能发送电子邮件。邮件已发送,但仍然返回一个错误,使我的应用崩溃。我相信这是由错误引起的:TypeError:无法阅读未定义的属性"捕获" 在exports.sendreportrequest.functions.https.onrequest(/srv/lib/index.js:57:9(

在我的代码中,我使用Mailgun的MailGun-JS模块发送电子邮件,并且我直接从文档中复制了代码。但是,Firebase要求我"正确处理承诺",即使用.catch来捕获任何错误。但是,一旦部署,Firebase似乎无法识别.send((作为承诺,并引发错误。

这是一个用于扑朔迷离的应用程序,每当我运行云功能时,我的应用程序崩溃,并且功能会在firebase日志中引发错误。

我已经在使用Blaze计划,因此外部API调用工作起作用。实际上,电子邮件已发送,但仍会引发错误,使我的应用程序崩溃。域和apikey没有问题,否则电子邮件不会发送。

我尝试使用onRequest,oncall和触发功能,但是它们都丢了相同的错误。

我尝试返回诺言而不是返回,但无济于事。现在我没有返回任何东西(或返回void(。

// MailGun cloud function
export const sendReportRequest = functions.https.onCall((data, context) => {
    console.log("REPORT SENT");
    const sendData = {
        from: 'Excited User <me@samples.mailgun.org>',
        to: 'xxxx@gmail.com',
        subject: 'Hello',
        text: 'Testing some Mailgun awesomeness!'
    };
    mg.messages().send(sendData, (error, body) => {
        if (error) { console.log("error!", error); }
        console.log("message sent:", body);
    })
        .catch((err) => { console.log("error", err); });
});

错误

TypeError: Cannot read property 'catch' of undefined
    at Object.<anonymous> (/srv/lib/index.js:55:9)
    at Generator.next (<anonymous>)
    at /srv/lib/index.js:7:71
    at new Promise (<anonymous>)
    at __awaiter (/srv/lib/index.js:3:12)
    at exports.sendReportRequest.functions.https.onRequest (/srv/lib/index.js:43:69)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:57:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:

这是因为发送可能没有返回承诺,而是使用回调方法。您可以注意到,因为您传递了一个函数,该函数会在mg.messages().send(sendData, *(error, body)* => {中收回返回数据。

这意味着没有catch短语可以追随它。您会在回调函数内部收到错误,因此只需在此处处理,或者如果您真的想要,则可以将其包裹起来,然后尝试将其丢弃,而不是在外面捕捉到:

try {
   mg.messages().send(sendData, (error, body) => {
       if (error) { throw new Error(error); }
       console.log("message sent:", body);
   })
} catch(e) {
 // handle error
}

作为附带说明,我去了MailGun-JS Github Repo尝试为您提供一个文档示例,我看到它已存档并且不再支持...您可能想考虑使用另一个库:(

另外,这是我发现的一篇不错的文章,可以很好地解释整个回调/承诺/async-watait混乱,有什么区别以及如何以及何时使用每种内容,如果您想阅读更多信息。

最新更新