PhantomJS错误处理

Jon*_*ink 12 javascript exception-handling phantomjs

我很难理解PhantomJS如何处理错误.

我有一个本地安装的Apache服务器运行(xampp),当我手动访问" http:// localhost / "时,我得到"It Works!" 页.

作为测试,我写了一个小文件(称为forceError.js),故意导致未经检查的异常:

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();
});
Run Code Online (Sandbox Code Playgroud)

当我使用以下方式运行时:

phantomjs.exe forceError.js
Run Code Online (Sandbox Code Playgroud)

首先,我获得"状态:成功",然后流程就会挂起.我没有看到调用page.onError或phantom.onError.

是否有一些属性或我需要打开以获得一般错误处理的东西?

我在Windows 7,PhantomJS版本2.0.0,并在我的"git bash"shell中运行它.

art*_*iak 7

在MacOS上测试并且经历了完全相同的行为,这确实有点不直观,很可能只是一个bug.奇怪的是,如果从最顶层调用未定义的函数,则可以phantom.onError正确调用1.

作为一种解决方法,您可以open使用a 来包装回调体try/catch.希望它能完成这项工作.

只是为了澄清:page.onError如果在执行所请求页面的代码时发生错误,则调用:而不是幻像脚本本身.我现在已经依赖page.onError了一段时间,它看起来非常稳定.(虽然有些错误只发生在phantomjs引擎中,但不会出现在常规浏览器中.)


1实际上:"phantom.onError"无限制地在控制台上打印,因为console.errorphantomjs不支持.


Jus*_*tte 6

接受的答案非常有用,但我会用代码示例补充它.

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

输出看起来类似于此屏幕剪辑: 产量

更新: 这似乎是一个特别的错误page.open.我注意到这phantom.onError是从回调中捕获的东西,而不是直接在里面page.open.这是另一种可能的解决方法.这至少允许您将所有错误处理代码放在一个位置,而不是拥有一堆try/catches.注意:你仍然需要page.onError内部的东西page.evaluate.

page.open(genericSignInPageUrl, function (status) {
    setTimeout(function () { //hack for page.open not hooking into phantom.onError
        if (status !== "success") {
            throw new Error("Unable to access network");
        }
        //do some stuff
    }, 0);
});
Run Code Online (Sandbox Code Playgroud)

当实际使用页面时,我已经开始使用它来确保我正在寻找的元素存在.由于我的代码是在回调中,onError方法工作正常.该waitFor方法的代码如下: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
    });
});
Run Code Online (Sandbox Code Playgroud)