Javascript 从 JSON.parse 捕获异常的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4467044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Proper way to catch exception from JSON.parse
提问by prostock
I'm using JSON.parse
on a response that sometimes contains a 404 response. In the cases where it returns 404, is there a way to catch an exception and then execute some other code?
我正在使用JSON.parse
有时包含 404 响应的响应。在它返回 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;
});
回答by UltraInstinct
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)!
}
}
回答by A-312
We can check error & 404 statusCode, and use try {} catch (err) {}
.
我们可以检查错误和 404 statusCode,并使用try {} catch (err) {}
.
You can try this :
你可以试试这个:
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();
Read more :
阅读更多 :
回答by ubuntugod
I am fairly new to Javascript. But this is what I understood:
JSON.parse()
returns SyntaxError
exceptions when invalid JSON is provided as its first parameter. So. It would be better to catch that exception as such like as follows:
我对 Javascript 还很陌生。但这就是我的理解:
当提供无效 JSON 作为其第一个参数时JSON.parse()
返回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);
}
}
The reason why I made the words "first parameter" bold is that JSON.parse()
takes a reviver function as its second parameter.
我将“第一个参数”这个词加粗的原因是它JSON.parse()
以一个reviver函数作为它的第二个参数。
回答by vivek java
You can try this:
你可以试试这个:
Promise.resolve(JSON.parse(response)).then(json => {
response = json ;
}).catch(err => {
response = response
});
回答by Jason Clay
This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.
如果 JSON.parse() 的参数无法解析为 JSON 对象,则此承诺将无法解决。
Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
});