robtaussig / react-use-websocket

React Hook for WebSocket communication
MIT License
1.6k stars 136 forks source link

Error handling for async url callback function #223

Closed danielmcmillan closed 8 months ago

danielmcmillan commented 8 months ago

I use an async function to get the WebSocket URL, which includes some credentials in the parameters. When the network is disconnected, this function may fail.

If my function throws an exception, then the exception is unhandled and it seems to prevent the re connection attempts from continuing. So after the network is connected again, it doesn't reconnect. If I return null, or "", then it causes another unhandled exception.

It's possible to workaround by returning some valid URL like "wss://null". It would be good if the exception from the url function were handled so that it doesn't break the reconnection behaviour.

robtaussig commented 8 months ago

Hi @danielmcmillan!

Thank you for taking the time to respond to some other issues. I initially had not implemented something like this as I felt it would be better to allow consumers of this hook to handle errors within the async url function, but I can see how returning anything besides a valid url is problematic, and requiring something like wss://null is a bit janky. I just published a solution (b7fafeb17020c17e3effa2b8682878c8e34d92f0) to 4.7.0.

I also updated documentation for async urls -- specifically, to take advantage of my solution, make sure to enable Options#retryOnError.

danielmcmillan commented 8 months ago

Thanks @robtaussig ! Appreciate your effort on this. I've tried out the new version and it's behaving as expected.