PhantomJS错误处理

乔纳森·布林克

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

我有一个本地安装的Apache服务器正在运行(xampp),当我手动访问“ http:// localhost / ”时,我得到了“有效!” 页。

作为测试,我编写了一个小文件(称为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

首先,我得到“状态:成功”,然后过程挂起。我没有看到page.onError或phantom.onError被调用。

是否需要一些属性或某些东西才能打开以进行常规错误处理?

我在Windows 7,PhantomJS 2.0.0版上,并在我的“ git bash” shell中运行它。

阿图尔·格泽西亚克

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

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

只是要澄清一下:page.onError如果在执行所请求页面的代码时发生错误而不是幻象脚本本身,则调用该方法。我已经依赖page.onError了一段时间了,它似乎运行稳定。(尽管某些错误仅在phantomjs引擎中发生,但在常规浏览器中不发生。)


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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章