Skip to content

Commit bd13183

Browse files
authored
fix: keep error messages for loose validation same as for strict validation (#22)
1 parent 7945e58 commit bd13183

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/index.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff 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) {

test/index.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)