处理异步JavaScript Chrome控制台错误

处理异步JavaScript Chrome控制台错误,javascript,google-chrome-extension,websocket,Javascript,Google Chrome Extension,Websocket,我在Chrome扩展中有一些Javascript,它每3秒钟运行一次,并尝试连接到本地WebSocket服务器 setInterval(attemptConnection, 3000); function attemptConnection() { try { var exampleSocket = new WebSocket("ws://localhost:8080"); exampleSocket.onmessage = function (event) {

我在Chrome扩展中有一些Javascript,它每3秒钟运行一次,并尝试连接到本地WebSocket服务器

setInterval(attemptConnection, 3000);

function attemptConnection() {

try {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);

    }
}

catch(err) {
//do something here
    }
我只希望在特定时间点运行本地WebSocket服务器。如果建立了连接,WebSocket服务器将发送一些JSON数据,javascript将立即使用这些数据

当我进入开发人员工具时,我看到我在控制台中多次遇到ERR_CONNECTION_被拒绝的情况,因为在该端点处显然没有任何东西,这是预期的行为。有没有办法抑制这些控制台输出或更好地处理此问题

编辑-更新了代码,但仍然会将错误输出到控制台

setInterval(attemptConnection, 3000);

function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);
        exampleSocket.send(event.data);

        exampleSocket.onerror = function () {
            //do nothing
        }
    }
}

无法使用
try/catch
捕获此错误,因为它是异步发生的。您应该使用
onerror
事件处理程序

function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);

    };
    exampleSocket.onerror = function() {
        // do nothing
    };
}

假设您必须使用
onerror
处理错误,您还应该处理
onclose
。 最简单的检查是错误代码
1000
,这意味着正常的插座关闭

exampleSocket.onclose = (event) => {
   if (event.code != 1000) {
      // "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
   }
}
虽然描述了错误代码的完整处理,但为了方便起见,我在这里列出:

     exampleSocket.onclose = (event) => {
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";
     }
exampleSocket.onclose=(事件)=>{
如果(event.code==1000)
原因=“正常关闭,意味着建立连接的目的已经实现。”;
else if(event.code==1001)
reason=“端点正在“离开”,例如服务器正在关闭或浏览器已经离开页面。”;
else if(event.code==1002)
reason=“由于协议错误,端点正在终止连接”;
否则如果(event.code==1003)
reason=“端点正在终止连接,因为它已接收到它无法接受的数据类型(例如,如果它接收到二进制消息,则仅理解文本数据的端点可能会发送此数据)。”;
否则如果(event.code==1004)
reason=“保留。具体含义可能在将来定义。”;
否则如果(event.code==1005)
原因=“没有实际存在的状态代码。”;
否则如果(event.code==1006)
原因=“连接异常关闭,例如未发送或接收关闭控制帧”;
else if(event.code==1007)
reason=“端点正在终止连接,因为它在消息中接收到与消息类型不一致的数据(例如,非UTF-8)[http://tools.ietf.org/html/rfc3629]文本信息中的数据)。”;
否则如果(event.code==1008)
reason=“端点终止连接是因为它收到一条“违反其策略”的消息。如果没有其他可接受的原因,或者需要隐藏有关策略的特定详细信息,则会给出此原因。”;
else if(event.code==1009)
reason=“端点正在终止连接,因为它收到的消息太大,无法处理。”;
else if(event.code==1010)//请注意,服务器不使用此状态代码,因为它可能导致WebSocket握手失败。
reason=“端点(客户端)正在终止连接,因为它希望服务器协商一个或多个扩展,但服务器没有在WebSocket握手的响应消息中返回这些扩展。
具体来说,需要的扩展是:“+event.reason; else if(event.code==1011) reason=“服务器正在终止连接,因为它遇到了阻止其完成请求的意外情况。”; else if(event.code==1015) 原因=“由于未能执行TLS握手(例如,无法验证服务器证书),连接已关闭。”; 其他的 原因=“未知原因”; }
var-exampleSocket=newwebsocket(“ws://localhost:8080”);
exampleSocket.onmessage=函数(事件){
var JsonObject=JSON.parse(event.data);
console.log(JsonObject)
例如socket.send(event.data);
exampleSocket.onerror=函数(){
//无所事事
}
}
exampleSocket.onclose=(事件)=>{
如果(event.code==1000)
原因=“正常关闭,意味着建立连接的目的已经实现。”;
else if(event.code==1001)
reason=“端点正在“离开”,例如服务器正在关闭或浏览器已经离开页面。”;
else if(event.code==1002)
reason=“由于协议错误,端点正在终止连接”;
否则如果(event.code==1003)
reason=“端点正在终止连接,因为它已接收到它无法接受的数据类型(例如,如果它接收到二进制消息,则仅理解文本数据的端点可能会发送此数据)。”;
否则如果(event.code==1004)
reason=“保留。具体含义可能在将来定义。”;
否则如果(event.code==1005)
原因=“没有实际存在的状态代码。”;
否则如果(event.code==1006)
原因=“连接异常关闭,例如未发送或接收关闭控制帧”;
else if(event.code==1007)
reason=“端点正在终止连接,因为它在消息中接收到与消息类型不一致的数据(例如,非UTF-8)[http://tools.ietf.org/html/rfc3629]文本信息中的数据)。”;
否则如果(event.code==1008)
reason=“端点正在终止连接,因为它收到了一条“违反其策略”的消息。如果没有,则会给出此原因
var timer = null;

function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");

        exampleSocket.onmessage = function (event) {
        timer = setTimeout(attemptConnection, 100);
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);
        exampleSocket.send(event.data);
    }
    exampleSocket.onerror = function (event) {
          console.log('error')
            //do nothin
          clearTimeout(timer)

      }
}

attemptConnection();