【问题标题】:Proper way to catch exception from JSON.parse从 JSON.parse 捕获异常的正确方法
【发布时间】:2011-05-26 21:45:32
【问题描述】:

我在有时包含 404 响应的响应中使用 JSON.parse。在返回 404 的情况下,有没有办法捕获异常,然后执行一些其他代码?

data = JSON.parse(response, function (key, value) {
    var type;
    if (value && typeof value === 'object') {
        type = value.type;
        if (typeof type === 'string' && typeof window[type] === 'function') {
            return new(window[type])(value);
        }
    }
    return value;
});

【问题讨论】:

  • 404 响应与XMLHttpRequest 相关,而不是JSON.parse 本身。如果你给我看代码 sippet,我也许可以帮助你。
  • data = JSON.parse(response,function (key, value) { var type; if (value && typeof value === 'object') { type = value.type; if (typeof type === 'string' && typeof window[type] === 'function') { return new (window[type])(value); } } return value;
  • 我在 iframe 中发布了一些内容,然后使用 json parse 读回 iframe 的内容...所以有时它不是 json 字符串

标签: javascript xmlhttprequest


【解决方案1】:

我将某些内容发布到 iframe 中,然后使用 json 解析读回 iframe 的内容...所以有时它不是 json 字符串

试试这个:

if(response) {
    try {
        a = JSON.parse(response);
    } catch(e) {
        alert(e); // error in the above string (in this case, yes)!
    }
}

【讨论】:

  • 如果 try 块包含更多语句,则可以通过 e.name == "SyntaxError" 识别异常,前提是您没有 eval。
  • 如果响应未定义怎么办?
  • @vini 然后你应该在 if 语句中添加一个 else 语句。
【解决方案2】:

我们可以检查错误和404状态码,并使用try {} catch (err) {}

你可以试试这个:

const req = new XMLHttpRequest();
req.onreadystatechange = function() {
    if (req.status == 404) {
        console.log("404");
        return false;
    }

    if (!(req.readyState == 4 && req.status == 200))
        return false;

    const json = (function(raw) {
        try {
            return JSON.parse(raw);
        } catch (err) {
            return false;
        }
    })(req.responseText);

    if (!json)
        return false;

    document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;
};
req.open("GET", "https://ipapi.co/json/", true);
req.send();

阅读更多:

【讨论】:

    【解决方案3】:

    我对 Javascript 还很陌生。但这就是我的理解: JSON.parse() 在提供无效 JSON 作为其 第一个参数 时返回 SyntaxError 异常。所以。最好像下面这样捕获该异常:

    try {
        let sData = `
            {
                "id": "1",
                "name": "UbuntuGod",
            }
        `;
        console.log(JSON.parse(sData));
    } catch (objError) {
        if (objError instanceof SyntaxError) {
            console.error(objError.name);
        } else {
            console.error(objError.message);
        }
    }
    

    之所以将“第一个参数”加粗,是因为JSON.parse() 将reviver 函数作为其第二个参数。

    【讨论】:

    • 我不明白你的最终 if/else。如果为真或假,则运行相同的代码:console.err(objError);
    • 它只是返回 objError,name as SyntaxError,而不是真正的错误部分。
    • 还有一件事。应该是:console.error() 不是 console.err()
    【解决方案4】:

    如果您正在为此寻找通用函数,请试一试。

    const parseJSON = (inputString, fallback) => {
      if (inputString) {
        try {
          return JSON.parse(inputString);
        } catch (e) {
          return fallback;
        }
      }
    };
    

    【讨论】:

      【解决方案5】:

      你可以试试这个:

      Promise.resolve(JSON.parse(response)).then(json => {
          response = json ;
      }).catch(err => {
          response = response
      });
      

      【讨论】:

        【解决方案6】:

        如果 JSON.parse() 的参数无法解析为 JSON 对象,则此承诺将无法解析。

        Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
            console.log(json);
        }).catch(err => {
            console.log(err);
        });
        

        【讨论】:

        • 但这并没有捕捉到JSON.parse抛出的异常
        • 所有你需要改变它是有效的就是改变JSON.parse(...)()=&gt;JSON.parse(...)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        • 2021-12-23
        • 2012-02-17
        • 2011-07-28
        相关资源
        最近更新 更多