Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling network errors with Puppeteer

Has anyone ever tried to handle network connexion errors with Puppeteer ? I tried by launching a random page and checking if I receive no errors until it works ( this try is in a for loop ) :

try{
        responseAwait = await page1.goto('https://www.residentadvisor.net/dj.aspx?country=01')
        } catch (err) {
        console.log('Page load fail : '+ err)
        if (err == 'Error: net::ERR_INTERNET_DISCONNECTED' || err == 'Error: net::ERR_NETWORK_CHANGED' || err == 'Error: net::ERR_NAME_NOT_RESOLVED'){
        let refreshIntervalId = setInterval(() =>{
           handleConnexionError(refreshIntervalId,page1)
        }, 5000) 
    }
    }

And here is the function that I use in order to check if the network is back :

async function handleConnexionError(refreshIntervalId,page1){
    console.log('Retrying to connect')
    let errorHandle = true
    await page1.goto('https://www.residentadvisor.net/dj.aspx?country=01').catch(() => {
        errorHandle = false
    })
    if (errorHandle) {
        console.log('Succesfully Reconnected')
        clearInterval(refreshIntervalId)
        return true
    }
    else {
        console.log('Connection Fail Retrying in 10 sec ...')
    }
}

But it's not working properly as the script keeps running and loops all over the for loop even though an error occured in the await...

like image 683
Nicolas Vriak Avatar asked Dec 31 '25 08:12

Nicolas Vriak


1 Answers

Here is an examle on How I am validating my app errors

GeneralFunctions.js

 validarErrores: (error, escenario)=>{
  console.log(`${error.toString()}`.bgRed);
  if (typeof escenario == `undefined`){
    return self.mensajeError(`Error 500 - Objeto indefinido`);
  }
  const { TimeoutError } = require('puppeteer/Errors');
  if (error instanceof TimeoutError) {
    if (error.toString().search(`Navigation Timeout`) != -1) {
      return self.mensajeError(`Se produjo un error de <strong> Timeout </strong> al navegar`);
    }
    for (pasos in escenario){
      for(prop in escenario[pasos]){
        if (error.toString().search(escenario[pasos][prop]) != -1) {
          return self.mensajeError(`Se produjo un error al <strong> no poder localizar </strong> el campo <strong>${escenario[pasos][prop]}</strong>`);
        }
      }
    }
    return self.mensajeError(`Error 500 - ${error.toString}`);
  }
  else if (error instanceof Error) {
    switch (true) {
      case (error.toString().includes(`ERR_INTERNET_DISCONNECTED`)):
        return self.mensajeError(`No hay conexión fisica a la red Local`);
        break;
      case (error.toString().includes(`ERR_CONNECTION_TIMED_OUT`)):
        return self.mensajeError(`La aplicacion no se encuentra en línea`);
        break;
      case (error.toString().includes(`ERR_CONNECTION_REFUSED`)):
        return self.mensajeError(`La dirección de la aplicacion no es correcta`);
        break;
      default:
        return self.mensajeError(`La aplicación a encontrado el ${error}`);
        break;
    }
  }
  // throw new Error(error);
}

main.js

(async () => {
          const puppeteer = require('puppeteer');
          const browser = await puppeteer.launch();
          const page = await browser.newPage();            
          try {
            await page.setViewport({ "width": 1280, "height": 720 });
            // Do someting
            } catch (e) {
              ${funcionesGenerales.validarErrores(e, selectores);
            }finally{
              await browser.close();
            }
        })();
like image 114
C Alonso C Ortega Avatar answered Jan 02 '26 21:01

C Alonso C Ortega



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!