javascript PhantomJS 错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31322029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:39:03  来源:igfitidea点击:

PhantomJS error handling

javascriptexception-handlingphantomjs

提问by Jonathan.Brink

I'm having a hard time understanding how PhantomJS handles errors.

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

I have a locally installed Apache server running (xampp), and when I manually visit "http://localhost/" I get the "It Works!" page.

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

As a test, I wrote a small file (called forceError.js) that purposely causes an unchecked exception:

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

When I run this using:

当我使用以下方法运行它时:

phantomjs.exe forceError.js

First I get "status: success" and then the process just hangs. I don't see either page.onError or phantom.onError being invoked.

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

Is there some property or something I need to turn on to get general error handling?

是否有一些属性或我需要打开才能进行一般错误处理?

I'm on Windows 7, PhantomJS version 2.0.0, and running this in my "git bash" shell.

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

采纳答案by artur grzesiak

Tested on MacOS and experienced exactly the same behaviour, which indeed is a bit unintuitive and most likely just a bug. The weird thing is that, if you call an undefined functionfrom the top most scope phantom.onErroris invoked correctly1.

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

As a workaround you can just wrap body of the opencallback with a try/catch. Hopefully it will do the job.

作为一种解决方法,您可以open使用try/catch. 希望它能完成这项工作。

Just to clarify: page.onErroris invoked if an error occurred while executing code of the requested page - not the phantom script itself. I have been relying on page.onErrorfor a while now and it seems to work pretty stable. (Although some errors only occur in phantomjs engine, but not in regularbrowsers.)

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



1Actually: "phantom.onError"gets printed on the console infinitely as console.erroris not supported by phantomjs.

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

回答by Justin Pavatte

The accepted answer was very helpful, but I'll supplement it with a code sample.

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

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 will look similar to this screen snip: Output

输出将类似于此屏幕截图: 输出

UPDATE:This appears to be a bug specifically with page.open. I noticed that phantom.onErrorwas catching things from callbacks, just not directly inside page.open. Here is another possible workaround. This at least allows you to have all the error handling code in one spot instead of having a bunch of try/catches. NOTE: You still need page.onErrorfor things inside page.evaluate.

更新:这似乎是一个专门针对page.open. 我注意到这phantom.onError是从回调中捕获的东西,而不是直接在page.open. 这是另一种可能的解决方法。这至少允许您在一个地方拥有所有错误处理代码,而不是一堆尝试/捕获。注意:你仍然需要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);
});

When actually doing things with the page, I've started using this to make sure the element I am looking for is there. Since my code is in a callback, the onErrormethods work fine. Code for the waitFormethod is here: https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js

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

回答by maxi-code

Your app hangs because it looks there is a loop when you call console.errorwithin phantom.onError. Check this: Phantomjs v2, consume huge memory+cpu, after throwing exception.

您的应用程序挂起是因为当您console.errorphantom.onError. 检查这个:Phantomjs v2,在抛出异常后消耗大量内存+cpu。