5

I want to have a javascript client process get the HTTP status code that a server is returning when the client makes a websocket upgrade request and that request is unsuccessful.

I have my server returning HTTP 400 to indicate that a websocket upgrade is unsuccessful.

I am using Google Chrome and when i open the developer console I can see the following message:

WebSocket connection to 'wss://' failed: Error during WebSocket handshake: Unexpected response code: 400

However, the onerror handler does not contain this message, it receives a 1006 error but does not indicate that the closure occured as a result of getting HTTP 400.

How does a javascript developer handle handshake errors? I would like to provide the client with an informative message when they get a handshake error.

I have put the websocket error below, it does not seem to contain anything that I can use to indicate that this error is a result of a websocket handshake error.

 Websocket Error: {"path":{"length":0},"cancelBubble":false,"returnValue":true,"srcElement":{"binaryType":"blob","protocol":"","extensions":"","bufferedAmount":0,"readyState":3,"url":"wss://<my address>","URL":"wss://<my address>"},"defaultPrevented":false,"timeStamp":1417828938039,"cancelable":false,"bubbles":false,"eventPhase":2,"currentTarget":{"binaryType":"blob","protocol":"","extensions":"","bufferedAmount":0,"readyState":3,"url":"wss://<my address>","URL":"wss://<my address>"},"target":{"binaryType":"blob","protocol":"","extensions":"","bufferedAmount":0,"readyState":3,"url":"wss://<my address>","URL":"wss://<my address>"},"type":"error"}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

5

I am afraid there is no way from Javascript to know the HTTP status code of the negotiation.

There are defined closing codes, and 1006 only means that the connection is closed abruptly, but the protocol even allows to close the connection without providing a reason. That, together with the readyState API, are the only tools you have to diagnosed the reason of the problem.

Community
  • 1
  • 1
vtortola
  • 34,709
  • 29
  • 161
  • 263
  • Yes, it appears to be impossible to distinguish whether the WebSocket connection failed because of invalid authentication credentials (I.e. those passed as a query parameter) or if the connection failed because of network failure or any other reason. Because of this limitation, I had to implement a secondary (custom) handshake to do authentication after the WebSocket connection was established (instead of using the standard WebSocket handshake). It's just not feasible to implement reliable authentication without transparency over success/failure states. – Jon Jan 29 '16 at 12:50