【问题标题】:Handling network errors with Puppeteer使用 Puppeteer 处理网络错误
【发布时间】:2018-07-17 14:27:30
【问题描述】:

有没有人尝试过使用 Puppeteer 处理网络连接错误?我尝试启动一个随机页面并检查在它工作之前是否没有收到任何错误(此尝试在 for 循环中):

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

这是我用来检查网络是否恢复的功能:

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 ...')
    }
}

但它无法正常工作,因为脚本继续运行并在整个 for 循环中循环,即使在 await 中发生错误...

【问题讨论】:

    标签: javascript asynchronous async-await puppeteer


    【解决方案1】:

    这是一个关于我如何验证我的应用程序错误的示例

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

    ma​​in.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();
                }
            })();
    

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多