JSON.parse から例外をキャッチする適切な方法 質問する

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

ベストアンサー1

iframe に何かを投稿し、json 解析で iframe の内容を読み取ります...そのため、json 文字列ではない場合があります

これを試して:

if (response) {
    let a;
    try {
        a = JSON.parse(response);
    } catch (e) {
        return console.error(e); // error in the above string (in this case, yes)!
    }
    // if no error, we can now keep using "a"
}

おすすめ記事