Puppeter:在异步函数中使用wait调用的javascript函数中抛出自定义错误消息
我正在使用Puppeter构建一个小应用程序来自动在线填写表单。我以Gmail为例,不用点击提交按钮就可以测试它的功能 我打开Gmail URL,使用名为Puppeter:在异步函数中使用wait调用的javascript函数中抛出自定义错误消息,javascript,node.js,error-handling,async-await,puppeteer,Javascript,Node.js,Error Handling,Async Await,Puppeteer,我正在使用Puppeter构建一个小应用程序来自动在线填写表单。我以Gmail为例,不用点击提交按钮就可以测试它的功能 我打开Gmail URL,使用名为findInputFieldByName的函数找到用户名输入字段。代码运行良好,网页打开,我可以看到木偶师打印test@gmail.com在用户名字段中 代码是: const puppeteer = require('puppeteer'); const gmailUrl='https://accounts.google.com/signin
findInputFieldByName
的函数找到用户名输入字段。代码运行良好,网页打开,我可以看到木偶师打印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
的输入字段。但是,如果我要使用不同的名称,例如Gmail登录页面上没有的identifier1,我希望代码抛出一条自定义错误消息,说“输入字段名称identifier1未找到”,代码应该停止
如果我改变
const userNameElement = await findInputFieldByName(page,'identifier').catch(error => {
console.log('The following error occurred: ' + error);
});
到
我得到以下错误:
主程序错误:TypeError:无法读取null的属性“type”
我理解这是因为函数findInputFieldByName
没有失败。它只是返回了一个空对象,因为没有名为identifier1的输入字段。当代码尝试键入电子邮件地址时,实际上失败了
但是,我的问题是如何从findInputFieldByName
函数中抛出错误,使其在const usernamelement=wait findInputFieldByName..
执行时停止
我尝试在findInputFiledByName
函数中使用承诺:
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));
}
});
}
但我得到了以下信息:
主程序错误:TypeError:无法读取未定义的属性“catch”
(节点:12332)未处理的PromisejectionWarning:错误:找不到输入名称标识符1
在C:\Users\test1.js:11:10
新承诺(我应该如何处理自定义错误?我是Javascript新手,非常感谢您的帮助。
在此处输入代码
首先,返回承诺,而不是将其分配给变量
const findInputFieldByName = (page, inputName) => {
return new Promise(((resolve, reject) => { // <-- Return it
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
});