【问题标题】:Http status not triggering on try and catch javascriptHttp 状态未在 try 和 catch javascript 上触发
【发布时间】:2019-06-12 23:42:20
【问题描述】:

我有将 JSON 发布到运行良好的 API 端点的功能。这是我的代码。

function sendValuesPageLoad(){
     var xhr = new XMLHttpRequest();
     xhr.onreadystatechange = function () {
        try {
          if (xhr.readyState === 4 && xhr.status === 200) {}
        } catch (ex) {
            alert('Error parsing response.');
        }
     }
     try {
        xhr.open("POST", "test.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     } catch (ex) {
        xhr.open("POST", "error.html?"+encodedString, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send();
     }
} 

如果 xhr.status 不等于 200,我想要实现的是执行进一步的操作。

但是捕获没有被触发。

有人可以帮忙吗?

提前致谢。

【问题讨论】:

  • 如果状态不是200,您可以使用throw
  • 你为什么期望它被触发?不能例外
  • @randomSoul 不明白你的意思。您可以编辑我的代码作为示例吗?
  • 对于您当前的代码没有例外,因此它不会执行您的 catch 块。如果你想在状态不是200 的情况下执行你的catch 块。您可以添加 if 语句来检查是否状态不是 200,然后在其中使用 throw 语句,这样您的 catch 块就会被执行。

标签: javascript html json xmlhttprequest


【解决方案1】:

XMLHttpRequest 带有自己的错误处理程序onerror。更新您的示例

function sendValuesPageLoad(){
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
       if (xhr.status === 200) {
          // successful
       } else {
          // fails
          throw new Error('Failed with status: ' + xhr.statusText);
       }
    }
    xhr.onerror = function () {
       throw new Error('There is a problem');
    }
    xhr.open("POST", "test.html?"+encodedString, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
}

您可以通过将其包装在 Promise 中并捕获任何错误来改进它

function sendValuesPageLoad(){
  return new Promise(function(resolve, reject) { 
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
       if (xhr.status === 200) {
          // successful
          resolve(xhr.response);
       } else {
          // fails
          reject(xhr.statusText);
       }
    }
    xhr.onerror = function () {
       reject(Error("Network Error"));
    }
    xhr.open("POST", "test.html?"+encodedString, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
  }
}

// use case
sendValuesPageLoad().then(function(response) { 
   // use your response here
}).catch(function(error) {
   // handle your error
});

【讨论】:

    【解决方案2】:

    function sendValuesPageLoad(){
       var encodedString = "value=2";
    
       var xhr = new XMLHttpRequest();
       console.log('UNSENT: ', xhr.status);
    
       xhr.open("POST", "test.html?" + encodedString, true);
       console.log('OPENED: ', xhr.status);
       
       xhr.onprogress = function () {
         console.log('LOADING: ', xhr.status);
       };
       
       xhr.setRequestHeader("Content-Type", "application/json");
       
       xhr.onload = function () {
         console.log('DONE: ', xhr.status);
         
         if(xhr.status === 200){
            alert("Status code is 200");
            
         }else{
             alert("Status code is not 200, but " + xhr.status);
         
            xhr.open("POST", "error.html?"+encodedString, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send();
         }
       };
       
       xhr.send();  
    }
    
    sendValuesPageLoad();

    【讨论】:

    • 我已经修改了答案
    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2019-01-12
    • 2015-06-15
    • 2011-07-12
    相关资源
    最近更新 更多