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
PhantomJS error handling
提问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.onError
is invoked correctly1.
在 MacOS 上测试并经历了完全相同的行为,这确实有点不直观,很可能只是一个错误。奇怪的是,如果您从最顶层的作用域调用未定义的函数,phantom.onError
则会正确调用1。
As a workaround you can just wrap body of the open
callback with a try/catch
. Hopefully it will do the job.
作为一种解决方法,您可以open
使用try/catch
. 希望它能完成这项工作。
Just to clarify: page.onError
is invoked if an error occurred while executing code of the requested page - not the phantom script itself.
I have been relying on page.onError
for 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.error
is 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:
UPDATE:This appears to be a bug specifically with page.open
. I noticed that phantom.onError
was 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.onError
for 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 onError
methods work fine. Code for the waitFor
method 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.error
within phantom.onError
. Check this: Phantomjs v2, consume huge memory+cpu, after throwing exception.
您的应用程序挂起是因为当您console.error
在phantom.onError
. 检查这个:Phantomjs v2,在抛出异常后消耗大量内存+cpu。