【问题标题】:PhantomJS - Handling Network ErrorPhantomJS - 处理网络错误
【发布时间】:2014-11-27 10:16:13
【问题描述】:

当我在调试模式下运行我的 PhantomJS 脚本时,有时会看到以下错误:[DEBUG] Network - Resource request error: 5 ("Operation cancelled")。

当我运行我的脚本 1000 次时,我有 1 到 2 次这个错误。我想在不以调试模式运行脚本的情况下捕获它,但我不知道如何!

我尝试了几个错误处理程序:

phantom.onError = function(msg, trace) {
  console.log("PhantomJS onError\n");
};

page.onError = function(msg, trace) {
  console.log("PhantomJS onError\n");
};

page.onResourceError = function(resourceError) {
  console.log("PhantomJS onResourceError\n");
};

page.onResourceTimeout = function(req) {
  console.error('PhantomJS onResourceTimeout\n');
};

page.onLoadFinished = function(status) {
  if (status != 'success') {
    console.error('PhantomJS onLoadFinished Error\n');
  }
};

你对我有什么想法吗?我怎样才能捕捉到这个错误?我在 Unix 上使用 PhantomJS 1.9.7 x64。

谢谢,

【问题讨论】:

  • 现在您拥有所有可能显示此错误的事件。您需要记录传递给处理程序的参数,以查看哪个是正确的。我的钱在page.onErrorpage.onResourceError 上。另外,捕捉是什么意思?您可能必须从事件处理程序本身停止基于此的进一步执行并重新启动。
  • 您好,是的,我想“捕获”错误以启动新的执行。我的问题是当我在调试中看到错误时没有调用处理程序!
  • 您好,没有人可以帮助我吗?谢谢。

标签: javascript phantomjs


【解决方案1】:

这个问题可能很老,但我今天遇到了同样的问题并找到了解决方法:

var numberOfRequests = 0;
page.onResourceReceived = function(response) {
    if (numberOfRequests === 0) {
        // if status of first resource is NULL there was a network error
        if (response.status === null) {
            console.log('[ERROR] Loading page failed: Network error');
            phantom.exit();
        }
    }

    numberOfRequests++;
};

使用 phantomJS 2.1 测试。希望这对其他人有帮助。

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2013-05-11
    • 1970-01-01
    相关资源
    最近更新 更多