javascript - Puppeteer:在异步函数中使用await 调用的javascript 函数中抛出自定义错误消息

标签 javascript node.js error-handling async-await puppeteer

我正在使用 puppeteer 构建一个小应用程序来自动在线填写表格。我使用 Gmail 作为示例来测试功能,而无需单击提交按钮。

我打开 Gmail URL 并使用名为 findInputFieldByName 的函数找到用户名输入字段。代码工作正常,网页打开,我可以看到 puppeteer 在用户名字段中打印 test@gmail.com

代码是:

const puppeteer = require('puppeteer');

const gmailUrl='https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin';
const userName='test@gmail.com';
const findInputFieldByName = (page,inputName) => {
    return page.$('input[name="'+inputName+'"]');
}

(async () => {
    try {
    const Browser = await puppeteer.launch({headless:false,
                                        defaultViewport:{width:600,height:800}
                                        });
    const page=await Browser.newPage();

    page.on('load', () => console.log('Page loaded ' + page.url()));
    await page.goto(gmailUrl);

    const userNameElement = await findInputFieldByName(page,'identifier').catch(error => {
       console.log('The following error occurred: ' + error);
       });
    await userNameElement.type(userName,{delay:50});
    } catch(e) {console.log('main program error:' + e);
    }

})();

正如您所看到的,代码正在返回的 HTML 中查找名称为 identifier 的输入字段。但是,如果我使用不同的名称,例如 identifier1,但该名称不在 Gmail 登录页面上,我希望代码抛出一条自定义错误消息,指出“找不到输入字段名称identifier1”,并且代码应该停止。

如果我改变

const userNameElement = await findInputFieldByName(page,'identifier').catch(error => {
           console.log('The following error occurred: ' + error);
           });

const userNameElement = await findInputFieldByName(page,'identifier1').catch(error => {
           console.log('The following error occurred: ' + error);
           });

我收到以下错误:

main program error:TypeError: Cannot read property 'type' of null

据我了解,这是因为函数 findInputFieldByName 没有失败。它只是返回一个 null 对象,因为没有名称为 identifier1 的输入字段。当代码尝试输入电子邮件地址时,它实际上失败了。

但是,我的问题是如何从 findInputFieldByName 函数中抛出错误,以便它在 const userNameElement = wait findInputFieldByName.. 执行时停止?

我尝试在 findInputFiledByName 函数中使用 Promise,如下所示:

const findInputFieldByName = (page,inputName) => {
    let promise=new Promise(function (resolve,reject){
    var elm= page.$('input[name="'+inputName+'"]');
    if (elm.length>0) {
        resolve(elm);
    } else {
        reject(Error('Could not find input name ' + inputName));
    }
});
}

但我收到以下消息:

main program error:TypeError: Cannot read property 'catch' of undefined (node:12332) UnhandledPromiseRejectionWarning: Error: Could not find input name identifier1

at C:\Users\test1.js:11:10

at new Promise (< anonymous >)

at findInputFieldByName (C:\Users\test1.js:6:14)

at C:\Users\test1.js:26:32

at < anonymous >

at process._tickCallback (internal/process/next_tick.js:188:7) (node:12332) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:12332) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我应该如何处理自定义错误?我是 Javascript 新手,非常感谢任何帮助。在此处输入代码

最佳答案

首先,返回 promise 而不是将其分配给变量。

const findInputFieldByName = (page, inputName) => {
  return new Promise(((resolve, reject) => { // <-- Return it

之后,如果需要,您可以抛出错误。

await findInputFieldByName(page,'identifier').catch(error => {
    throw ('The following error occurred: ' + error) // <-- pass the error to main program
});

关于javascript - Puppeteer:在异步函数中使用await 调用的javascript 函数中抛出自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52346651/

相关文章:

javascript - 文本总是两行

javascript - Mongo 返回完整数据,而 Mongoose 不返回相对数据

javascript - 按多个空格拆分字符串 NodeJS

php - MySQL DELETE 随机且非常罕见地失败

c#专业错误处理

javascript - REGEX:删除以下日期模式末尾的逗号

javascript - 将数据推送到对象时出现 Angular 4 错误

javascript - MongoDB - 返回 X 条随机记录

javascript - 如何在 mongodb-native findAndModify 中使用变量作为字段名?

php - 无法处理 PHP 的 SoapServer->handle() 方法中的错误