pladaria / reconnecting-websocket

Reconnecting WebSocket. For Web, React Native, cli (Node.js)
MIT License
1.23k stars 199 forks source link

Can't get access to 403 Forbidden error #126

Open MichaelHipp opened 4 years ago

MichaelHipp commented 4 years ago

If the ws is trying to re-connect but getting rejected because of status 403 there seems to be no way to catch this error in the error handler. Status 403 would often mean it is trying to connect with an expired authorization (e.g. cookie). This can't be resolved by more reconnect attempts and some other action must be taken. Is there a way to get status 403 to bubble up to the 'error' event listener?

neilcarv commented 4 years ago

Hey @MichaelHipp , did you find an alternate way to get around this? I have the same query.

MichaelHipp commented 4 years ago

No I did not. Looking at the browser Websocket api, I'm not sure the actual status code is even exposed. I ended up discontinuing my use of reconnecting-websocket and just writing my own connect/reconnect logic using the Websocket api. So far it is working well, tho not in production yet.

Basically if I get any kind of error from the websocket, I ping the backend with a https verification url to see if we are authorized. If I get a 403, I know we just aren't authorized and some higher power will have to intervene. If I get a 200, I attempt to reconnect the ws. If I get anything else, I figure it is some anomaly and try again after a time.

Caveat, I have control of both front and back end and know well what the back end will send. YMMV.

jruales commented 4 years ago

I'm also looking for a way to access the error code returned from the server.

The server responds with a socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");, and the browser does know that it got a 401, since it displays WebSocket connection to 'ws://localhost................................' failed: HTTP Authentication failed; no valid credentials available. However, when I set the option debug: true in the ReconnectingWebSocket to see the logs, the log just says RWS> error event undefined instead of saying what type of error it was.

I also tried adding a listener for the WebSocket's "error" event, but the error object that's passed in doesn't have the error code in it.

jruales commented 4 years ago

Apparently, the client can't have access to this information by design, according to this StackOverflow answer