I'm slightly confused about the need (or otherwise) to add page listeners in puppeteer, in order to catch all errors.
In the following snippet, I've added handlers for the 'error'
and 'pageerror'
events. But won't these be caught by the try/catch
around await page.goto()
? What does the try/catch
catch that isn't caught by the handlers, and vice versa? If the handlers are reacting to errors that aren't caught by try/catch
, how do I handle those properly without getting an uncaughtException
, since these errors happen outside the normal async/await
flow? I really want to use the same error handling logic for all errors... i.e. await
all errors, and handle any error the same way, not just some of them.
(async () => {
try {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
page.on('error', error => {
console.error('Page on error:', error);
});
page.on('pageerror', error => {
console.error('Page on pageerror:', error);
});
await page.goto('https://www.example.com');
await page.screenshot({ path: './tmp/example.png' });
await browser.close();
} catch (err) {
console.error('Try/catch error:', err);
}
})();
I have tried wrapping the whole thing in a new Promise((resolve, reject) => { ... })
and then calling reject(error)
in the page error handlers:
try {
await new Promise((resolve, reject) => {
(async () => {
try {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
page.on('error', error => {
console.error('Page on error:', error);
reject(error);
});
page.on('pageerror', error => {
console.error('Page on pageerror:', error);
reject(error);
});
await page.goto('https://www.example.com');
await page.screenshot({ path: './tmp/example.png' });
await browser.close();
resolve();
} catch (err) {
reject(err);
}
})();
});
} catch (err) {
console.error('Try/catch error:', err);
}
But I'm still getting some odd uncaughtException
errors (in my real code, which I can't yet reproduce in a simple example)... I can't figure out if the new Promise()
approach is completely wrong in this context... or what the correct approach is.