@@ -618,7 +618,14 @@ function initAsClient(websocket, address, protocols, options) {
618
618
const isUnixSocket = parsedUrl . protocol === 'ws+unix:' ;
619
619
620
620
if ( ! parsedUrl . host && ( ! isUnixSocket || ! parsedUrl . pathname ) ) {
621
- throw new Error ( `Invalid URL: ${ websocket . url } ` ) ;
621
+ const err = new Error ( `Invalid URL: ${ websocket . url } ` ) ;
622
+
623
+ if ( websocket . _redirects === 0 ) {
624
+ throw err ;
625
+ } else {
626
+ emitErrorAndClose ( websocket , err ) ;
627
+ return ;
628
+ }
622
629
}
623
630
624
631
const isSecure =
@@ -687,9 +694,7 @@ function initAsClient(websocket, address, protocols, options) {
687
694
if ( req === null || req . aborted ) return ;
688
695
689
696
req = websocket . _req = null ;
690
- websocket . _readyState = WebSocket . CLOSING ;
691
- websocket . emit ( 'error' , err ) ;
692
- websocket . emitClose ( ) ;
697
+ emitErrorAndClose ( websocket , err ) ;
693
698
} ) ;
694
699
695
700
req . on ( 'response' , ( res ) => {
@@ -709,7 +714,14 @@ function initAsClient(websocket, address, protocols, options) {
709
714
710
715
req . abort ( ) ;
711
716
712
- const addr = new URL ( location , address ) ;
717
+ let addr ;
718
+
719
+ try {
720
+ addr = new URL ( location , address ) ;
721
+ } catch ( err ) {
722
+ emitErrorAndClose ( websocket , err ) ;
723
+ return ;
724
+ }
713
725
714
726
initAsClient ( websocket , addr , protocols , options ) ;
715
727
} else if ( ! websocket . emit ( 'unexpected-response' , req , res ) ) {
@@ -811,6 +823,19 @@ function initAsClient(websocket, address, protocols, options) {
811
823
} ) ;
812
824
}
813
825
826
+ /**
827
+ * Emit the `'error'` and `'close'` event.
828
+ *
829
+ * @param {WebSocket } websocket The WebSocket instance
830
+ * @param {Error } The error to emit
831
+ * @private
832
+ */
833
+ function emitErrorAndClose ( websocket , err ) {
834
+ websocket . _readyState = WebSocket . CLOSING ;
835
+ websocket . emit ( 'error' , err ) ;
836
+ websocket . emitClose ( ) ;
837
+ }
838
+
814
839
/**
815
840
* Create a `net.Socket` and initiate a connection.
816
841
*
0 commit comments