File tree Expand file tree Collapse file tree 2 files changed +27
-1
lines changed
Expand file tree Collapse file tree 2 files changed +27
-1
lines changed Original file line number Diff line number Diff line change @@ -174,7 +174,23 @@ export class ConnectionString extends URLWithoutHost {
174174 if ( typeof password === 'string' ) authString += `:${ password } ` ;
175175 if ( authString ) authString += '@' ;
176176
177- super ( `${ protocol . toLowerCase ( ) } ://${ authString } ${ DUMMY_HOSTNAME } ${ rest } ` ) ;
177+ try {
178+ super ( `${ protocol . toLowerCase ( ) } ://${ authString } ${ DUMMY_HOSTNAME } ${ rest } ` ) ;
179+ } catch ( err : any ) {
180+ if ( looseValidation ) {
181+ // Call the constructor again, this time with loose validation off,
182+ // for a better error message
183+ // eslint-disable-next-line no-new
184+ new ConnectionString ( uri , {
185+ ...options ,
186+ looseValidation : false
187+ } ) ;
188+ }
189+ if ( typeof err . message === 'string' ) {
190+ err . message = err . message . replace ( DUMMY_HOSTNAME , hosts ) ;
191+ }
192+ throw err ;
193+ }
178194 this . _hosts = hosts . split ( ',' ) ;
179195
180196 if ( ! looseValidation ) {
Original file line number Diff line number Diff line change @@ -191,6 +191,16 @@ describe('ConnectionString', () => {
191191 expect ( cs . port ) . to . equal ( '' ) ;
192192 expect ( cs . href ) . to . equal ( 'mongodb://:password@x/' ) ;
193193 } ) ;
194+
195+ it ( 'throws good error messages for invalid URLs' , ( ) => {
196+ try {
197+ // eslint-disable-next-line no-new
198+ new ConnectionString ( '-://:password@x' , { looseValidation : true } ) ;
199+ expect . fail ( 'missed exception' ) ;
200+ } catch ( err : any ) {
201+ expect ( err . message ) . to . equal ( 'Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"' ) ;
202+ }
203+ } ) ;
194204 } ) ;
195205} ) ;
196206
You can’t perform that action at this time.
0 commit comments