Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

javascript - 从JSON.parse捕获异常的正确方法(Proper way to catch exception from JSON.parse)

I'm using JSON.parse on a response that sometimes contains a 404 response.

(我在有时包含404响应的响应中使用JSON.parse 。)

In the cases where it returns 404, is there a way to catch an exception and then execute some other code?

(在它返回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;
});
  ask by prostock translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i post something into an iframe then read back the contents of the iframe with json parse...so sometimes it's not a json string

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

Try this:

(试试这个:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...