PhantomJS 错误处理

PhantomJS error handling

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

我在本地安装了 Apache 服务器 运行ning (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();
});

当我运行这个使用:

phantomjs.exe forceError.js

首先我得到 "status: success" 然后进程挂起。我没有看到 page.onError 或 phantom.onError 被调用。

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

我正在使用 Windows 7,PhantomJS 版本 2.0.0,运行在我的 "git bash" shell.

中安装它

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

作为解决方法,您可以使用 try/catch 包装 open 回调的主体。希望它能完成这项工作。

澄清一下:如果在执行所请求页面的代码时发生错误,则会调用 page.onError - 而不是幻影脚本本身。 我已经依赖 page.onError 一段时间了,它似乎工作得相当稳定。 (虽然有些错误只出现在 phantomjs 引擎中,但在 常规 浏览器中不会出现。)


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

接受的答案非常有帮助,但我将用代码示例对其进行补充。

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

输出类似于此屏幕截图:

更新: 这似乎是 page.open 的一个错误。我注意到 phantom.onError 正在从回调中捕捉东西,而不是直接在 page.open 中。这是另一种可能的解决方法。这至少允许您将所有错误处理代码放在一个位置,而不是一堆 try/catches。注意:对于 page.evaluate.

中的内容,您仍然需要 page.onError
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);
});

在实际处理页面时,我已经开始使用它来确保我要查找的元素在那里。由于我的代码处于回调中,因此 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
    });
});

您的应用挂起是因为当您在 phantom.onError 中调用 console.error 时它看起来有一个循环。检查这个:Phantomjs v2, consume huge memory+cpu, after throwing exception.