如何使用Javascript处理被客户端阻止的错误?

如何使用Javascript处理被客户端阻止的错误?,javascript,jquery,ajax,adblock,Javascript,Jquery,Ajax,Adblock,我的目标是发现广告拦截器。我发现了两个很好的例子,比如 当广告服务呼叫被广告阻止时,我们得到错误“err\u blocked\u by\u client” 我希望通过以下方式处理此错误: var xhr = new XMLHttpRequest(); try { xhr.open("GET","http://static.adzerk.net/ados.js", false); xhr.onreadystatechange = function (oEvent) { if (xhr.

我的目标是发现广告拦截器。我发现了两个很好的例子,比如

当广告服务呼叫被广告阻止时,我们得到错误“err\u blocked\u by\u client”

我希望通过以下方式处理此错误:

var xhr = new XMLHttpRequest();
try
{
xhr.open("GET","http://static.adzerk.net/ados.js", false);
xhr.onreadystatechange = function (oEvent) {  
    if (xhr.readyState === 4) {  
        if (xhr.status === 200) {  
          console.log(xhr.responseText)  
        } else {  
           console.log("Error", xhr.statusText);  
        }  
    }
};
xhr.send();
}
catch(error)
{
    console.log("ConsoleLog \n " + JSON.stringify(xhr));
    console.log("Error Catched" + error);
}
但在这种情况下,我无法识别catch块上的错误原因

请让我知道更好的选择来处理这个错误或我在这个代码中的错误


谢谢

您需要将
xhr
变量放在您的try之外。它在
JSON.stringify(xhr)
上失败-因为
xhr
超出范围。您需要使用OneError错误处理程序来处理异步XMLHttpRequest。您还需要从传递给onreadystatechange的函数中删除oEvent参数。见下文:

var xhr = new XMLHttpRequest();

try
{    
    xhr.open("GET","http://static.adzerk.net/ados.js", true);

    xhr.onreadystatechange = function () {  
        if (xhr.readyState === 4) {  
            if (xhr.status === 200) {  
              console.log(xhr.responseText)  
            } else {  
               console.log("Error", xhr.statusText);  
            }  
        }            
    };    
    xhr.onerror = function(e) {
        console.log("Error Catched" + e.error);
    };    

    xhr.send();        
}
catch(error)
{
    console.log("ConsoleLog \n " + JSON.stringify(xhr));
    console.log("Error Catched" + error);
}

很抱歉,我在编写有问题的代码时犯了错误。我也是这样做的。但它不起作用。没有在日志中的任何地方我得到“错误被客户端阻止”。@ManishPatwari好的,我看到了问题。您需要使用OneError处理程序-因为这是一个异步调用。请给我代码。我试过这样做:xhr.onerror=function(error){console.log(“on error”);};但是这也不起作用。@ManishPatwari在调用send之前应该注册onerror事件。我已经编辑了答案。我试过了,但仍然没有成功。请找到截图