Jam3sn
Jam3sn

Reputation: 1087

How to handle invalid URL / IP's in websockets?

I'm using HTML / Javascript web sockets to communicate with a python server program. Now I have the option to change the server's IP via clean UI and I have a .onerror function that handles with connection errors, however this doesn't handle initial errors. What I mean by this is if I were to enter a completely invalid address, it wont even attempt to connect with it (which is fine) and spit out and error like: [Error] WebSocket network error: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.). How can I handle this error so I can say, popup a message for example?

Here's a brief overview of my JS script.

function updateDevice(id, ipUI){
    if ("WebSocket" in window){
        var ws = new WebSocket(serverIP);

// Here is where I need to handle the bad address right?

        ws.onopen = function(){
            ws.send(id);
        };

        ws.onmessage = function (evt){ 
            var received_msg = evt.data;
        };

// This function ws.onerror doesnt handle bad addresses.

        ws.onerror = function(){
            document.getElementById("error_msg").style.display='block';
        };
    }else{
        alert("This site doesnt support your browser...");
    };
};

Upvotes: 2

Views: 2387

Answers (1)

Connor Peet
Connor Peet

Reputation: 6265

You could wrap the new WebSocket in a try/catch:

try {
    new WebSocket(serverIP);
} catch (e) {
    if (e instanceof DOMException) {
        alert('Invalid address!');
    } else {
        throw e;
    }
}

Upvotes: 2

Related Questions