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.
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.
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 pageawait browser.close();} catch (error) {console.error('An error occurred:', error);await page.screenshot({ path: "output/error.png" }); // Take screenshot of the page}})();
puppeteer
.try
block and all its arguments.Note: If the error occurs, then it will save an
error.png
file. Otherwise, it will save ascreenshot.png
.
Free Resources