处理同步 XHR 连接错误

Handle sync XHR connection errors

我一直在搜索,但找不到有关此事的任何文档:使用 Microsoft 提供的 XMLHttpRequest 接口发出同步 HTTP 请求时,如何处理 connection/network 相关错误。

我在 wscript 下工作,制作一个 HTTP 请求包装器,我想知道我将如何处理不同的 connection/network 错误 (与服务器相反-response-reported errors) 对于使用 XMLHttpRequest 接口的 HTTP 请求。

澄清一下,我不仅想知道是否发生了 connection/network 错误,而且还想知道如何确定发生的错误类型,以便不同的错误会导致不同的处理。例如 connection timeout 错误、connection refused 错误和 dns resolve 错误

// httpObj is a valid Microsoft/ActiveX provided XMLHttpRequest object name
function () {

    var request = new ActiveXObject(httpObj);
    request.open(this.httpMethod, this.httpUrl, false);
    request.timeout = this.httpTimeout;
    request.setRequestHeader("Connection", "close");
    request.send(this.httpData);

    // How would I handle connection/network-related errors?
}

(我从未使用过 ActiveX 请求,但我认为它们的工作方式与 XMLHttpRequest 相同;如果我错了,我会很乐意删除此答案。)

如果脚本能够从服务器读取 HTTP 错误响应,请求对象的 status 属性 将被设置为 HTTP 错误代码(404500, 等)和 statusText 属性 将设置为对 HTTP 错误的描述。

否则,status 属性 将是 0,表示网络故障或缺少跨源 CORS 权限。

function () {
    ...
    request.send(this.httpData);

    if(request.status == 0) {
        // no response from server, error or otherwise
    }
    if(request.status == 404) {
        // there was a response from the server; it was a 404
    }
}

XHR API 没有公开任何区分网络错误类型的方法。 ActiveX 对象可能有一些方法可以做到这一点,但我不知道它会是什么,如果它存在的话。