2010-12-17 87 views
167

我对有时包含404响应的响应使用JSON.parse。在返回404的情况下,是否有办法捕获异常并执行其他代码?从JSON.parse捕获异常的正确方法

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; 
}); 
+3

404响应与'XMLHttpRequest',而不是'JSON.parse'本身有关。 如果您向我展示代码片段,我可以帮助您。 – 2010-12-17 01:54:23

+0

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); } } }返回值; – prostock 2010-12-17 02:06:30

+0

我将某些内容发布到iframe中,然后回读内容的iframe与json解析...所以有时它不是一个json字符串 – prostock 2010-12-17 02:07:25

回答

256

我寄东西到iframe然后读回iframe的内容使用JSON解析......所以有时它不是一个JSON字符串

试试这个:

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

如果try块包含更多的语句,你可以通过e.name ==“SyntaxError”来识别异常,只要你没有eval。 – user1158559 2015-12-20 20:54:53

+0

感谢它的工作我 – Darkcoder 2018-03-07 08:54:14

3

您可以试试这个:

var jsonString = "b"; 
 

 
try { 
 
    a = JSON.parse(jsonString); 
 
} catch (e) { 
 
    alert(e); // You get an error. 
 
}

-1

如果JSON.parse()的参数不能被解析为JSON对象,这个承诺就不会解决。

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

但是这并没有捕获'JSON.parse'抛出的异常 – Abdel 2017-11-08 10:17:33