Proper way to catch exception from JSON.parse

后端 未结 5 1957
轻奢々
轻奢々 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 + "
    Your isp : " + json.org; }; req.open("GET", "https://ipapi.co/json/", true); req.send();

    Read more :

    • Catch a 404 error for XHR

提交回复
热议问题