@@ -630,19 +630,26 @@ function initAsClient(websocket, address, protocols, options) {
630
630
631
631
const isSecure = parsedUrl . protocol === 'wss:' ;
632
632
const isUnixSocket = parsedUrl . protocol === 'ws+unix:' ;
633
+ let invalidURLMessage ;
633
634
634
635
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' ;
638
642
}
639
643
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 ) ;
643
646
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
+ }
646
653
}
647
654
648
655
const defaultPort = isSecure ? 443 : 80 ;
@@ -724,9 +731,7 @@ function initAsClient(websocket, address, protocols, options) {
724
731
if ( req === null || req . aborted ) return ;
725
732
726
733
req = websocket . _req = null ;
727
- websocket . _readyState = WebSocket . CLOSING ;
728
- websocket . emit ( 'error' , err ) ;
729
- websocket . emitClose ( ) ;
734
+ emitErrorAndClose ( websocket , err ) ;
730
735
} ) ;
731
736
732
737
req . on ( 'response' , ( res ) => {
@@ -746,7 +751,15 @@ function initAsClient(websocket, address, protocols, options) {
746
751
747
752
req . abort ( ) ;
748
753
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
+ }
750
763
751
764
initAsClient ( websocket , addr , protocols , options ) ;
752
765
} else if ( ! websocket . emit ( 'unexpected-response' , req , res ) ) {
@@ -849,6 +862,19 @@ function initAsClient(websocket, address, protocols, options) {
849
862
} ) ;
850
863
}
851
864
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
+
852
878
/**
853
879
* Create a `net.Socket` and initiate a connection.
854
880
*
0 commit comments