简体   繁体   English

如何捕获PhantomJS提取的页面中生成的JavaScript错误?

[英]How do I capture JavaScript errors generated in a page fetched by PhantomJS?

I have a PhantomJS script that loads a local HTML file, injects some javascript files, then executes some javascript in the context of the page. 我有一个PhantomJS脚本,它加载一个本地HTML文件,注入一些javascript文件,然后在页面的上下文中执行一些javascript。 The javascript that runs generates an exception, but I only get output from the console, which doesn't seem to distinguish between an error and a normal log and doesn't have file, line numbers or a stacktrace. 运行的javascript会生成异常,但我只从控制台获取输出,这似乎不区分错误和普通日志,并且没有文件,行号或堆栈跟踪。

What I need is a way to capture or otherwise distinguish these errors. 我需要的是捕获或以其他方式区分这些错误的方法。 I have already tried: 我已经尝试过了:

  • Wrapping my PhantomJS script in a try-catch 将我的PhantomJS脚本包装在try-catch中
    • Result: nothing is thrown far enough to be caught by this 结果:没有任何东西被抛到足以被这个抓住
  • Define a window.onerror function 定义一个window.onerror函数
    • Result: nothing happens. 结果:没有任何反应。 WebKit does not implement an onerror event on the window WebKit没有在窗口上实现onerror事件

I would prefer to be able to retrieve the error object itself so that I can retrieve the stacktrace. 我希望能够检索错误对象本身,以便我可以检索堆栈跟踪。

I think there were issues with window.onerror not properly working in WebKit (https://bugs.webkit.org/show_bug.cgi?id=8519). 我认为window.onerror在WebKit中没有正常工作存在问题(https://bugs.webkit.org/show_bug.cgi?id=8519)。 Don't know if this has been fixed at all, and if so, if the QT WebKit version is already up-to-date. 不知道这是否已经修复,如果是,那么QT WebKit版本是否已经是最新版本。

However, you should be able to catch the exceptions thrown in your code. 但是,您应该能够捕获代码中抛出的异常。 If you are using something like webPage.evaluate(...) to run your code, you cannot wrap the complete call in a try/catch block, since the script is evaluated in a different context and the errors will not appear in the main execution context. 如果您使用类似webPage.evaluate(...)东西来运行代码,则无法将整个调用封装在try / catch块中,因为脚本是在不同的上下文中进行评估的,并且错误不会出现在主要内容中执行上下文。 Insteadyou will need to catch the errors in page execution context. 相反,您需要捕获页面执行上下文中的错误。 Unfortunately, there is no way of accessing any functions defined in the main context, we therefore have to explicitly write the wrapping code around your code to be executed. 遗憾的是,无法访问主上下文中定义的任何函数,因此我们必须在代码周围显式编写包装代码以执行。

The following is a modified example of the phantomwebintro.js file as included in the PhantomJS source. 以下是PhantomJS源中包含的phantomwebintro.js文件的修改示例。 It loads an HTML page, inserts a script and then runs some code in the page context (here with a line throwing a type error). 它加载一个HTML页面,插入一个脚本然后在页面上下文中运行一些代码(这里有一行抛出一个类型错误)。 This code is wrapped with a try/catch block and will return the wrapped result or error object to the main context. 此代码包含try / catch块,并将包装结果或错误对象返回到主上下文。

...

// Load an HTML page:
page.open("http://www.phantomjs.org", function(status) {
    if (status == "success") {

        // Inject some scripts:
        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {

            // Run your own code in the loaded page context:
            var resultWrapper = page.evaluate(function() {
                var wrapper = {};
                try {
                    // Your code goes here
                    // ...

                    var x = undefined.x; // force an error

                    // store your return values in the wrapper
                    wrapper.result = 42;
                } catch(error) {
                    wrapper.error = error;
                }
                return wrapper;
            });

            // Handle the result and possible errors:
            if (resultWrapper.error) {
                var error = resultWrapper.error;
                console.log("An error occurred: " + error.message);
                // continue handling the error
                // ...
            } else {
                var result = resultWrapper.result;
                // continue using the returned result
                // ...
            }

            ...

        });
    }
});

...

The solution? 解决方案? return true ! return true

      // Error tracking
      page.onError = function(msg, trace) {
          console.log('= onError()');
          var msgStack = ['  ERROR: ' + msg];
          if (trace) {
            msgStack.push('  TRACE:');
            trace.forEach(function(t) {
              msgStack.push('    -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
            }); 
          }   
          console.log(msgStack.join('\n'));

          // Consider error fully handled
          return true;
      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM