@@ -630,19 +630,26 @@ function initAsClient(websocket, address, protocols, options) {
630630
631631 const isSecure = parsedUrl . protocol === 'wss:' ;
632632 const isUnixSocket = parsedUrl . protocol === 'ws+unix:' ;
633+ let invalidURLMessage ;
633634
634635 if ( parsedUrl . protocol !== 'ws:' && ! isSecure && ! isUnixSocket ) {
635- throw new SyntaxError (
636- 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'
637- ) ;
636+ invalidURLMessage =
637+ 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"' ;
638+ } else if ( isUnixSocket && ! parsedUrl . pathname ) {
639+ invalidURLMessage = "The URL's pathname is empty" ;
640+ } else if ( parsedUrl . hash ) {
641+ invalidURLMessage = 'The URL contains a fragment identifier' ;
638642 }
639643
640- if ( isUnixSocket && ! parsedUrl . pathname ) {
641- throw new SyntaxError ( "The URL's pathname is empty" ) ;
642- }
644+ if ( invalidURLMessage ) {
645+ const err = new SyntaxError ( invalidURLMessage ) ;
643646
644- if ( parsedUrl . hash ) {
645- throw new SyntaxError ( 'The URL contains a fragment identifier' ) ;
647+ if ( websocket . _redirects === 0 ) {
648+ throw err ;
649+ } else {
650+ emitErrorAndClose ( websocket , err ) ;
651+ return ;
652+ }
646653 }
647654
648655 const defaultPort = isSecure ? 443 : 80 ;
@@ -724,9 +731,7 @@ function initAsClient(websocket, address, protocols, options) {
724731 if ( req === null || req . aborted ) return ;
725732
726733 req = websocket . _req = null ;
727- websocket . _readyState = WebSocket . CLOSING ;
728- websocket . emit ( 'error' , err ) ;
729- websocket . emitClose ( ) ;
734+ emitErrorAndClose ( websocket , err ) ;
730735 } ) ;
731736
732737 req . on ( 'response' , ( res ) => {
@@ -746,7 +751,15 @@ function initAsClient(websocket, address, protocols, options) {
746751
747752 req . abort ( ) ;
748753
749- const addr = new URL ( location , address ) ;
754+ let addr ;
755+
756+ try {
757+ addr = new URL ( location , address ) ;
758+ } catch ( e ) {
759+ const err = new SyntaxError ( `Invalid URL: ${ location } ` ) ;
760+ emitErrorAndClose ( websocket , err ) ;
761+ return ;
762+ }
750763
751764 initAsClient ( websocket , addr , protocols , options ) ;
752765 } else if ( ! websocket . emit ( 'unexpected-response' , req , res ) ) {
@@ -849,6 +862,19 @@ function initAsClient(websocket, address, protocols, options) {
849862 } ) ;
850863}
851864
865+ /**
866+ * Emit the `'error'` and `'close'` event.
867+ *
868+ * @param {WebSocket } websocket The WebSocket instance
869+ * @param {Error } The error to emit
870+ * @private
871+ */
872+ function emitErrorAndClose ( websocket , err ) {
873+ websocket . _readyState = WebSocket . CLOSING ;
874+ websocket . emit ( 'error' , err ) ;
875+ websocket . emitClose ( ) ;
876+ }
877+
852878/**
853879 * Create a `net.Socket` and initiate a connection.
854880 *
0 commit comments