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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (233)

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

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

代码是:

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);
    }

})();

代码正在查找其名称identifier在返回的HTML中的输入字段。但是,如果我要使用不同的名称,例如识别码1,这不在Gmail登录页面上,我希望代码抛出一条自定义错误消息“ 输入字段名称标识符1未找到”,代码应该停止。

如果我改变

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);
           });

收到以下错误:

主程序错误:TypeError:无法读取属性'type'的null

findInputFiledByName函数中使用promises :

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.

该如何解决呢?

提问于
用户回答回答于

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

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
});

扫码关注云+社区

领取腾讯云代金券