Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I've been developing browser-based multi player game for a while now and I've been testing different ports accessibility in various environment (client's office, public wifi etc.). All is going quite well, except one thing: I can't figure out is how to read error no. or description when onerror event is received.

Client websocket is done in javascript.

For example:

// Init of websocket
websocket = new WebSocket(wsUri);
websocket.onerror = OnSocketError;
...etc...
// Handler for onerror:
function OnSocketError(ev)
    output("Socket error: " + ev.data);

'output' is just some utility function that writes into a div.

What I am getting is 'undefined' for ev.data. Always. And I've been googling around but it seems there's no specs on what params this event has and how to properly read it.

Any help is appreciated!

Note, it's by-design that you can't get useful error information out of websocket: stackoverflow.com/a/31003057/771768 – Carl Walsh Feb 3, 2019 at 7:33

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
    websocket = new WebSocket("ws://yourDomainNameHere.org/");
    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See https://www.rfc-editor.org/rfc/rfc6455#section-7.4.1
        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 [https://www.rfc-editor.org/rfc/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).";
            reason = "Unknown reason";
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    alert("Websocket is not supported by your browser");
    return;
websocket.send("Yo wazzup");
websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Yea my answer is really hypothetical unless they are in some strange condition where they can receive more codes, I'm not sure why it has so many upvotes since I mentioned that at the top of my answer – Phylliida Mar 29, 2017 at 21:57 You might want to use an object literal with the event code and reason as key/value pairs for better code readability – Water Man Apr 25, 2022 at 13:09

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

I am using Chrome and the reason is "", The odd thing is that the F12 developers tool gives a lot more information. – Dr.YSG Jun 16, 2014 at 18:20 @Dr.YSG This is not strange at all. The error message in the developer tools is meant for the user of the browser so it can contain sensitive information. OTOH some random JavaScript code is generally not trusted. Otherwise you could write a worm (like a port scanner or a DDoS script) and just spread it via some random ad network. – jpc Jan 12, 2015 at 14:03

Potential stupid fix for those who throw caution to the wind: return a status code. The status code can be viewed from the onerror event handler by accessing the message property of the argument received by the handler. I recommend going with the 440s--seems to be free real estate.

"Unexpected server response: 440"

Little bit of regex does the trick:

const socket = new WebSocket(/* yuh */);
socket.onerror = e => {
  const errorCode = e.message.match(/\d{3}/)[0];
  // errorCode = '440'
  // make your own rudimentary standard for error codes and handle them accordingly

Might be useful in a pinch, but don't come crying to me for any unforeseen repercussions.

e.message is of course undefined. Question is about browsers WebSocket developer.mozilla.org/en-US/docs/Web/API/WebSocket not about npm package ws npmjs.com/package/ws – mikep Nov 10, 2022 at 9:27

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.