Handling network errors with Puppeteer

可紊 提交于 2021-02-18 08:11:20

问题


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...


回答1:


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();
            }
        })();


来源:https://stackoverflow.com/questions/48661420/handling-network-errors-with-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!