从JSON.parse捕获异常的正确方法

时间:2010-12-17 01:52:33

标签: javascript xmlhttprequest

我在有时包含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;
});

5 个答案:

答案 0 :(得分:367)

  

我将一些东西发布到iframe然后用json解析回读iframe的内容...所以有时候它不是一个json字符串

试试这个:

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

答案 1 :(得分:7)

我们可以检查错误& 404 statusCode,并使用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();

了解更多:

答案 2 :(得分:2)

我对Java相当陌生。但这是我的理解: 当提供无效的JSON作为其第一个参数时,def this(sparkContext: SparkContext, batchDuration: Duration) = { this(sparkContext, null, batchDuration) } 返回JSON.parse()异常。所以。最好像下面这样捕获该异常:

SyntaxError

之所以将“第一个参数”一词设为粗体,是因为try { let sData = ` { "id": "1", "name": "UbuntuGod", } `; console.log(JSON.parse(sData)); } catch (objError) { if (objError instanceof SyntaxError) { console.err(objError.name); } else { console.err(objError.message); } } 将齐磊函数作为第二个参数。

答案 3 :(得分:-1)

您可以尝试以下方法:

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

答案 4 :(得分:-5)

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

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