你能捕捉到连接错误吗?

Can you catch a connection error?

我尝试了很多方法来捕捉这段代码的错误,但不知何故我无法捕捉到它的错误。

我尝试了 trycatch(err) 方法,但错误只是弹出。也找不到有关如何捕获服务器连接错误的文章。它们出现在我的控制台日志中,但我似乎无法捕捉到它们。这是我到目前为止尝试过的方法...我尝试过的方法之一。

function timrec(){
try{
var time;
var inter1sec = setInterval(frame, 1000);
function frame() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        time = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = "Date is: "+time.d+"-"+time.m+"-"+time.y+" <br> Time is: " +time.h+":"+time.mi+":"+time.s+ " <br> day of the week is: "+ time.dow + "<br>";

};  }

xmlhttp.open("GET", "date.php",true);
xmlhttp.send();

}
}
catch(err){
alert("Warning! Connection error! Server might be down!");
}
}

我使用代码按时间间隔获取服务器时间,但当我尝试刷新我的 WAMP 服务器以模拟服务器连接失败时似乎无法捕捉到它的错误。

有没有可能抓住那个?

如果可以可以分享一下吗?如果不是... thennnnn 这将是一个失败。要么,要么我的教授只是向我提出了一个棘手的问题或其他问题。不会是第一次了。 :/

使用此代码:

var xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET", "http://www.google.com", true);

xmlhttp.onreadystatechange = function () {  
    if (xmlhttp.readyState === 4) {  // request completed. we have some results
        if (xmlhttp.status === 200) {  
          console.log(xmlhttp.responseText)  
        } else {  
           console.log("Oops", xmlhttp.statusText);  
        }  
    }  
}; 

xmlhttp.send(null);