2015-07-09 18 views
10

Sto avendo difficoltà a capire come PhantomJS gestisce gli errori.PhantomJS la gestione degli errori

Ho un server Apache installato localmente (xampp) e quando visito manualmente "http://localhost/" ottengo il messaggio "Funziona!" pagina.

Come prova, ho scritto un piccolo file (chiamati forceError.js) che causa volutamente un'eccezione incontrollato:

var page = require('webpage').create(), 
    url = 'http://localhost/'; 

page.onError = function(msg, trace) { 
    console.log("page.onError"); 
    var msgStack = ['ERROR: ' + msg]; 
    if (trace && trace.length) { 
    msgStack.push('TRACE:'); 
    trace.forEach(function(t) { 
     msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : '')); 
    }); 
    } 
    console.error(msgStack.join('\n')); 
}; 

phantom.onError = function(msg, trace) { 
    console.log("phantom.onError"); 
    var msgStack = ['PHANTOM ERROR: ' + msg]; 
    if (trace && trace.length) { 
    msgStack.push('TRACE:'); 
    trace.forEach(function(t) { 
     msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : '')); 
    }); 
    } 
    console.error(msgStack.join('\n')); 
    phantom.exit(1); 
}; 

page.open(url, function (status) { 
    console.log("status: " + status); 

    // an undefined function 
    thisShouldForceAnError(); 
}); 

Quando ho eseguito questo utilizzando:

phantomjs.exe forceError.js 

Prima ottengo " status: success "e quindi il processo si blocca. Non vedo né page.onError o phantom.onError invocato.

C'è qualche proprietà o qualcosa che ho bisogno di accendere per ottenere la gestione generale errore?

Sono su Windows 7, PhantomJS la versione 2.0.0, e l'esecuzione di questo nel mio guscio "git bash".

+1

Potrebbe essere un problema con GitHub. Sembra un bug in PhantomJS 2. –

+0

@ArtjomB. Buona idea: https://github.com/lichunqiang/lichunqiang.github.io/issues/13 –

+0

@ArtjomB. grazie: https://github.com/ariya/phantomjs/issues/13403 –

risposta

7

provata su MacOS e sperimentato esattamente lo stesso comportamento, che è davvero un po 'poco intuitivo e molto probabilmente solo un bug. La cosa strana è che, se si chiama una funzione non definita dalla cima più ambito phantom.onError viene richiamato correttamente .

Per ovviare al problema, è possibile includere il corpo della callback open con un try/catch. Spero che faccia il lavoro.

Giusto per chiarire: page.onError viene richiamato se si è verificato un errore durante l'esecuzione del codice della pagina richiesta, non lo script fantasma stesso. Ho fatto affidamento su page.onError da un po 'e sembra funzionare abbastanza stabile. (Anche se alcuni errori si verificano solo nel motore phantomjs, ma non in regolari browser.)


realtà: "phantom.onError" viene stampato sulla console infinitamente come console.error non è supportato da phantomjs.

+0

Prova 'return true;' sul 'page.onError' –

6

La risposta accettata è stata molto utile, ma la completerò con un esempio di codice.

page.open("https://www.google.com/", function (status) { 
    try { 
     if (status !== "success") { 
      console.log("Unable to access network"); 
     } else { 
      //do some stuff with the DOM 
     }   
    } catch (ex) { 
     var fullMessage = "\nJAVASCRIPT EXCEPTION"; 
     fullMessage += "\nMESSAGE: " + ex.toString(); 
     for (var p in ex) { 
      fullMessage += "\n" + p.toUpperCase() + ": " + ex[p]; 
     } 
     console.log(fullMessage); 
    } 
}); 

output sarà simile a questa schermata snip: Output

UPDATE: Questo sembra essere un bug in particolare con page.open. Ho notato che il numero phantom.onError stava recuperando le cose dai callback, ma non direttamente all'interno di page.open. Ecco un'altra soluzione possibile. Questo almeno ti permette di avere tutto il codice di gestione degli errori in un punto invece di avere un sacco di try/catch. NOTA: è ancora necessario page.onError per le parti all'interno di page.evaluate.

Quando faccio effettivamente le cose con la pagina, ho iniziato a usarlo per assicurarmi che l'elemento che sto cercando sia lì.Poiché il mio codice è in un callback, i metodi onError funzionano correttamente. Codice per il metodo waitFor è qui: https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js

page.open(genericSignInPageUrl, function() { 
    waitFor(function() { 
     return page.evaluate(function() { 
      return document.getElementById("idOfElementToIndicatePageLoaded"); 
     }); 
    }, function() { 
     //do some stuff with the page 
    }); 
});