Proper way to catch exception from JSON.parse

后端 未结 5 1941
轻奢々
轻奢々 2020-12-02 07:13

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 exec

相关标签:
5条回答
  • 2020-12-02 07:54

    We can check error & 404 statusCode, and use 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 :

    • Catch a 404 error for XHR
    0 讨论(0)
  • 2020-12-02 08:02

    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:

    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.

    0 讨论(0)
  • 2020-12-02 08:02

    You can try this:

    Promise.resolve(JSON.parse(response)).then(json => {
        response = json ;
    }).catch(err => {
        response = response
    });
    
    0 讨论(0)
  • 2020-12-02 08:04

    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

    Try this:

    if(response) {
        try {
            a = JSON.parse(response);
        } catch(e) {
            alert(e); // error in the above string (in this case, yes)!
        }
    }
    
    0 讨论(0)
  • 2020-12-02 08:06

    This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

    Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
        console.log(json);
    }).catch(err => {
        console.log(err);
    });
    
    0 讨论(0)
提交回复
热议问题