使用 YUI3 时捕获 Javascript 语法错误

发布于 2024-08-11 23:43:22 字数 968 浏览 5 评论 0原文

我正在使用 YUI 团队提供的稍微修改过的示例代码。当我的源以 JSON 以外的内容响应(或者只是有 JSON 语法错误)时,我的浏览器 (Safari) 会中止脚本处理,从而阻止我通知用户出现问题。

我绝对不是 JS 大师,所以这段代码可能比它应该的要丑陋得多。代码大致是:

YUI().use("dump", "node", "datasource-get", "datasource-jsonschema", function(Y) {
  var myDataSource = new Y.DataSource.Get({
    source:"/some/json/source/?"}),
    myCallback = {
      success: function(e){
        myResponse = e.response;
        doSomething(myDataSource);
      },
      failure: function(e){
        Y.get("#errors").setContent("<li>Could not retrieve data: " + e.error.message + "</li>");
      }
    };

  myDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
    schema: {
      resultListLocator: "blah.list",
      resultFields: ["user", "nickname"]
    }
  });
  myDataSource.sendRequest("foo=bar", myCallback);
}

我尝试将“var myDataSource”块包装在 try/catch 中,并且我还尝试包装整个 YUI().use() 块。

是否可以捕获语法错误?我是否必须将一体化的 DataSource.Get 调用替换为单独的 IO 和解析调用?

I'm using slightly modified sample code provided by the YUI team. When my source responds with something other than JSON (or just has a JSON syntax error) my browser (Safari) aborts script processing, preventing me from notifying the user there was a problem.

I'm definitely no JS guru, so this code may be a lot uglier than it has to be. The code is, roughly:

YUI().use("dump", "node", "datasource-get", "datasource-jsonschema", function(Y) {
  var myDataSource = new Y.DataSource.Get({
    source:"/some/json/source/?"}),
    myCallback = {
      success: function(e){
        myResponse = e.response;
        doSomething(myDataSource);
      },
      failure: function(e){
        Y.get("#errors").setContent("<li>Could not retrieve data: " + e.error.message + "</li>");
      }
    };

  myDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
    schema: {
      resultListLocator: "blah.list",
      resultFields: ["user", "nickname"]
    }
  });
  myDataSource.sendRequest("foo=bar", myCallback);
}

I've tried wrapping the "var myDataSource" block in a try/catch, and I've also tried wrapping the whole YUI().use() block.

Is it possible to catch syntax errors? Do I have to replace the all-in-one DataSource.Get call with separate IO and parse calls?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱本泡沫多脆弱 2024-08-18 23:43:23

由于您正在请求本地脚本,因此您可以在 try/catch 或 Y.DataSource.IO + Y.DataSchema.JSON (+ Y.JSON) 内使用 Y.io + Y.JSON.parse。

DataSource.Get 的好处是它避免了同源策略。然而,它的安全性和灵活性较差。如果没有必要,您应该避免使用它。

DataSource.Get 的约定是服务器支持 JSONP。其工作方式是 Get 使用 src=(您提供的 url)&callback=someDataSourceFunction 将脚本节点添加到页面。

浏览器将请求该 url 处的资源,并且会发生以下两种情况之一:

  1. 服务器将以 someDataSourceFunction({"all":"your data"}); 形式响应 JavaScript 字符串;否则
  2. 服务器将返回一些无法解析为 JavaScript 的文本。

无论哪种情况,该字符串都被视为脚本节点的内容 - 它被解析并执行。如果无法解析,浏览器会抛出错误。这是没有办法阻止的。虽然 JSONP 在技术上不受真正 JSON 的规范约束(即使无效的 JSON 也应该解析和执行),但您应该始终使用纯 JSON,并始终使用服务器端库来生成 JSON 输出(查看 http://json.org 获取每种可以想象的语言的库列表)。不要手卷 JSON。它只会导致数小时的调试。

Since you are requesting a local script, you can use Y.io + Y.JSON.parse inside a try/catch or Y.DataSource.IO + Y.DataSchema.JSON (+ Y.JSON).

The benefit of DataSource.Get is that it avoids the Same Origin Policy. However, it is less secure and less flexible. If it is not necessary, you should avoid using it.

The contract of DataSource.Get is that the server supports JSONP. The way this works is that Get adds a script node to the page with a src=(the url you provided)&callback=someDataSourceFunction.

The browser will request the resource at that url and one of two things will happen:

  1. the server will respond with a JavaScript string in the form of someDataSourceFunction({"all":"your data"}); or
  2. the server will return some text that can't be parsed as JavaScript.

In either event, that string is treated as the contents of a script node--it is parsed and executed. If it cannot be parsed, the browser will throw an error. There's no stopping this. While JSONP is technically not under the spec constraints of true JSON (even invalid JSON should parse and execute), you should always use pure JSON, and always use a server side lib to generate the JSON output (look on http://json.org for a list of libs in every conceivable language). Don't hand-roll JSON. It only leads to hours of debugging.

羁绊已千年 2024-08-18 23:43:23

问题可能是在 YUI 有机会报告失败之前,错误就发生在浏览器的某个级别(Javascript 解析)。

众所周知,在 Safari 中捕获此类错误非常困难,因为它没有实现 window.onerror。为了用我的 Javascript 库 bezen.org 捕获更多错误,我在异步的地方添加了 try/catch触发代码:

  • 动态脚本加载(相当于您的 JSON 下载)
  • setTimeout/setTimer:我包装并替换了这些浏览器函数以插入记录错误的 try/catch

您可能有兴趣查看相应模块的源代码,这可能对您有用或作为解决问题的提示:

The problem is probably that the error happens at some level in the browser (Javascript parsing) before YUI even gets the occasion to report a failure.

It is notoriously hard to catch this kind of error in Safari, which does not implement window.onerror. In order to catch more errors with my Javascript library, bezen.org, I added try/catch in places where asynchronous code is triggered:

  • dynamic script loading (equivalent to your JSON download)
  • setTimeout/setTimer: I wrapped and replaced these browser functions to insert a try/catch which logs errors

You may be interested in having a look at the source code of the corresponding modules, which may be useful to you as is or as hints for the resolution of your problem:

恋你朝朝暮暮 2024-08-18 23:43:23

也许在你“做某事”之前尝试一下:

try
{
   var test = YAHOO.lang.JSON.parse(jsonString); 
   ...
}
catch (e)
{
   alert('invalid json');
}

Maybe try this before you "doSomething":

try
{
   var test = YAHOO.lang.JSON.parse(jsonString); 
   ...
}
catch (e)
{
   alert('invalid json');
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文