Automatically Close Pages in Puppeteer on Error Occurrence

I need assistance with ensuring that Puppeteer pages are closed automatically when an error occurs. Sometimes, when a page crashes unexpectedly, the normal closure process isn’t executed, leaving resources open and causing further issues. I am looking for a way to implement an error handler that reliably shuts down the page even during failures. Below is an example snippet that demonstrates one method:

(async function executeTask() {
  let tab = await browser.newPage();
  await tab.setViewport({ width: 1024, height: 768 });
  await tab.goto('http://example.com', { timeout: 60000 });
  await tab.screenshot({ path: './images/screenshot.png', fullPage: true });
  await tab.close();
})();

I have faced similar issues with Puppeteer where an error in the page leads to resource leakage. One technique that worked for me was wrapping the page operations in a try-catch block and ensuring that in the finally block I attempt to close the page regardless of any failure. In addition to that, I registered event listeners on the page to detect unexpected crashes. This combination has significantly reduced the chance of leaving orphaned pages and helped maintain a predictable cleanup process even under error conditions.