How to detect and handle error pages in Puppeteer?

To detect and handle error pages in Puppeteer, you can use the page.on('response') event to monitor responses from the server and check for error codes or messages. Here's a basic example:

const puppeteer = require('puppeteer'); async function checkForErrors(url) { const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on('response', async (response) => { if (response.status() >= 400) { console.error(`Error loading ${url}: ${response.status()} ${response.statusText()}`); // Handle error here } }); await page.goto(url); await browser.close(); } checkForErrors('https://example.com');

In this example, we are using the page.on('response') event to check the response status code for any errors. If an error is detected (status code 400 or higher), we print an error message to the console. You can handle the error in any way that makes sense for your application, such as reloading the page, taking a screenshot, or logging the error.

Additionally, you can also handle specific error pages using Puppeteer's page.evaluate() function to check for specific elements on the page that indicate an error, and then take appropriate action based on that detection.

Remember to handle errors gracefully and consider adding error handling logic to your Puppeteer scripts to ensure that they continue to run smoothly even when encountering errors.