@@ -618,7 +618,14 @@ function initAsClient(websocket, address, protocols, options) {
618618 const isUnixSocket = parsedUrl . protocol === 'ws+unix:' ;
619619
620620 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+ }
622629 }
623630
624631 const isSecure =
@@ -687,9 +694,7 @@ function initAsClient(websocket, address, protocols, options) {
687694 if ( req === null || req . aborted ) return ;
688695
689696 req = websocket . _req = null ;
690- websocket . _readyState = WebSocket . CLOSING ;
691- websocket . emit ( 'error' , err ) ;
692- websocket . emitClose ( ) ;
697+ emitErrorAndClose ( websocket , err ) ;
693698 } ) ;
694699
695700 req . on ( 'response' , ( res ) => {
@@ -709,7 +714,14 @@ function initAsClient(websocket, address, protocols, options) {
709714
710715 req . abort ( ) ;
711716
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+ }
713725
714726 initAsClient ( websocket , addr , protocols , options ) ;
715727 } else if ( ! websocket . emit ( 'unexpected-response' , req , res ) ) {
@@ -811,6 +823,19 @@ function initAsClient(websocket, address, protocols, options) {
811823 } ) ;
812824}
813825
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+
814839/**
815840 * Create a `net.Socket` and initiate a connection.
816841 *
0 commit comments