Hi, last days we have problems with websockets. Warning and errors like this are in console:
WebSocket connection to 'wss://example.com/' failed: WebSocket is closed before the connection is established.
11:43:48.653 client.js:421 WebSocket connection to 'wss://example.com/' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
I try to catch this kind of errors by adding connectionCallback but it is not raised, and when I look at sources https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/client.ts#L517 it looks like onError is empty.
Is there any way how to catch these problems?
Thank you Petr
it'd be nice if they exposed it as an option, but they do expose the native socket:
const subscriptionClient = new SubscriptionClient(...)
subscriptionClient.client.onerror = (e) => {console.log('fire in the wall')};
Just adding to this, the apollo-link-error lib also doesn't capture any websocket connection errors but the app i was working on needed to dispatch redux actions to inform the user of whether they were connected or not.
@mattkrick is right that it is exposed, but the client is reinstantiated on connection and so using subscriptionClient.client.onerror is not viable.
Thankfully, there are now hooks directly on subscriptionClient so i was able to build a redux middleware like this:
export const network = ({ dispatch }) => {
client.onConnected(() => dispatch(networkStatusChanged(true)))
client.onDisconnected(() => dispatch(networkStatusChanged(false)))
client.onReconnected(() => dispatch(networkStatusChanged(true)))
return next => action => {
return next(action)
}
}
@ashconnell that's very true! It takes some care because websocket clients can't really be reinstated like EventSource clients. When the websocket close event fires, you can't restart it, you just have to call new WebSocket() and put your onerror handler back on it.
I recently released a lib to handle clients who are behind websocket-blocking firewalls by using a SSE or WebRTC fallback. I still haven't released the server protocol, but maybe it'll provide some inspo? https://github.com/mattkrick/trebuchet-client/blob/master/src/SocketTrebuchet.ts#L47-L52
Most helpful comment
it'd be nice if they exposed it as an option, but they do expose the native socket: