【问题标题】:Why does crockford create this type of error function in his json_parse function?为什么 crockford 会在他的 json_parse 函数中创建这种类型的错误函数?
【发布时间】:2016-01-15 14:10:47
【问题描述】:

https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js 在此链接中,Douglas Crockford 创建了一个 json_parse 函数,该函数由一个 IIFE 中的许多函数组成。内部函数之一是以下错误抛出函数:

    error = function (m) {
        throw {
            name: 'SyntaxError',
            message: m,
            at: at,                // the variable he stores his incrementing index
            text: text             // the string from the JSON object
        };
    },

我对这个误差函数很感兴趣,因为我从来没有见过这样写的误差函数。当我用这样的无用输入测试错误函数时:

json_parse('{123: 123}');

我收到以下错误:

/Users/<user>/src/crockford.js:30
            throw {
            ^
SyntaxError: Bad string

但是如果我回到原来的错误函数并通过删除 at 和 text 值来修改错误函数,如下所示:

        error = function (m) {
            throw {
                name: 'SyntaxError',
                message: m
            };
        },

我最终得到相同的错误消息。

如果出现错误时不显示错误消息,那么在错误消息中添加索引和输入文本有什么意义?我对他的误差函数的结构有什么遗漏,目的是什么?

【问题讨论】:

  • 如果不看更多代码就无法判断。
  • 所以基本上你在问扔一个物体有什么意义?
  • 当 JSON 已经成为标准 5 年多了,你为什么还要使用那个库来解析?
  • 我只是在研究他的源代码来学习,我很好奇我可以从他的错误函数中拿走和实现什么

标签: javascript json error-handling


【解决方案1】:

默认错误处理程序不会显示这些属性,但可以通过 catch 块中的代码访问它们,或者您可以在 Javascript 调试器中查看它们。

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2021-08-09
    • 2021-05-31
    • 2010-10-14
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多