[英]Proper way to catch exception from JSON.parse
我在有時包含 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;
});
我將一些內容發布到 iframe 中,然后使用 json 解析讀回 iframe 的內容......所以有時它不是一個 json 字符串
試試這個:
if(response) {
try {
a = JSON.parse(response);
} catch(e) {
alert(e); // error in the above string (in this case, yes)!
}
}
我們可以檢查 error & 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();
閱讀更多 :
我對 Javascript 還很陌生。 但這就是我的理解: JSON.parse()
返回SyntaxError
異常時,將無效的 JSON 作為其第一個參數提供。 所以。 最好像下面這樣捕獲該異常:
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 函數作為它的第二個參數。
如果您正在為此尋找通用的 function,請試一試。
const parseJSON = (inputString, fallback) => {
if (inputString) {
try {
return JSON.parse(inputString);
} catch (e) {
return fallback;
}
}
};
我建議您將此用作ES6 最佳實踐。 使用Error
object
try { myResponse = JSON.parse(response); } catch (e) { throw new Error('Error occured: ', e); }
以上回答也有幫助,
反應鈎子 2021
const history = useHistory()
history.go(-1)
你可以試試這個:
Promise.resolve(JSON.parse(response)).then(json => {
response = json ;
}).catch(err => {
response = response
});
如果 JSON.parse() 的參數無法解析為 JSON 對象,則此承諾將無法解決。
Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.