How do you handle errors and exceptions in Puppeteer?

Puppeteer, a Node.js package, offers a high-level API for controlling headless browsers (without a graphical user interface) or full browsers via the Chrome DevTools Protocol. However,while using Puppeteer, we might run into errors and exceptions that we must manage appropriately.

In this Answer, we will learn how Puppeteer handles failures and exceptions.

Try-catch blocks

Use standard JavaScript try-catch blocks to capture errors and exceptions while executing Puppeteer instructions. This can assist you in handling errors and exceptions and stop your script from crashing.

Code example

import puppeteer from 'puppeteer'
(async () => {
try {
const browser = await puppeteer.launch({
headless: 'new',
args: [
"--no-sandbox",
"--disable-gpu",
'--disable-setuid-sandbox'
]
});
const page = await browser.newPage();
await page.goto('https://www.educative.io/answers/');
await page.screenshot({ path: "output/screenshot.png" }); // Take screenshot of the page
await browser.close();
} catch (error) {
console.error('An error occurred:', error);
await page.screenshot({ path: "output/error.png" }); // Take screenshot of the page
}
})();

Code explanation

  • Line 1: Imports puppeteer.
  • Lines 4–12: Define the try block and all its arguments.
  • Lines 13–19: Defines the opening of the Educative Answer’s browser. If it runs successfully, these lines will take a screenshot and close the browser.
  • Lines 20–23: Defines the catch block. If the error occurs, it will also take its screenshot.

Note: If the error occurs, then it will save an error.png file. Otherwise, it will save a screenshot.png.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved