在使用 Puppeteer 进行页面操作时,我们可以通过 page.on
方法来添加监听器来捕获页面发生的事件。然而,如果监听器的回调函数之外发生了错误,我们需要使用 try-catch
块来捕获这些错误。
下面是一个示例代码,演示如何使用 try-catch
块来捕获回调函数之外的错误:
const puppeteer = require('puppeteer');
async function main() {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// 添加 page.on 监听器
page.on('console', (message) => {
console.log(`Message from page: ${message.text()}`);
});
// 模拟一个错误
const error = new Error('This is an error outside the page.on callback');
throw error;
await browser.close();
} catch (error) {
console.error(`Error occurred: ${error}`);
}
}
main();
在上面的示例中,我们模拟了一个错误,并在 throw
语句中抛出。然后我们使用 try-catch
块来捕获这个错误,并在 catch
语句中进行处理。这样可以确保即使在回调函数之外发生了错误,也能够正确地捕获并处理它们。
注意,在回调函数内部发生的错误可以直接通过 try-catch
块来捕获,而不需要特别处理。上面的示例中,我们只关注了回调函数之外发生的错误。