Skip to content

Commit a3d1597

Browse files
fix(correct-ts-specifiers): don't crash when specifier doesn't resolve (#60)
1 parent 6132fcd commit a3d1597

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

recipes/correct-ts-specifiers/src/fexists.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,5 +137,13 @@ describe('fexists', () => {
137137
assert.equal(await fexists(parentPath, specifier), false);
138138
assert.equal(mock__access.calls[0].arguments[0], specifier, RESOLVED_SPECIFIER_ERR);
139139
});
140+
141+
it('should return `false` when the specifier can’t be resolved', async () => {
142+
mock__resolveSpecifier.mockImplementationOnce(function MOCK__resolveSpecifier(_pp, _specifier) {
143+
throw Object.assign(new Error('ERR_MODULE_NOT_FOUND'), { code: 'ERR_MODULE_NOT_FOUND' });
144+
});
145+
146+
assert.equal(await fexists(parentPath, 'noexists'), false);
147+
});
140148
});
141149
});

recipes/correct-ts-specifiers/src/fexists.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,13 @@ export function fexists(
1111
parentPath: FSAbsolutePath | ResolvedSpecifier,
1212
specifier: Specifier,
1313
) {
14-
const resolvedSpecifier = resolveSpecifier(parentPath, specifier) as FSAbsolutePath;
14+
let resolvedSpecifier: FSAbsolutePath;
15+
try {
16+
resolvedSpecifier = resolveSpecifier(parentPath, specifier) as FSAbsolutePath;
17+
} catch (err) {
18+
if ((err as NodeJS.ErrnoException).code !== 'ERR_MODULE_NOT_FOUND') throw err;
19+
return false;
20+
}
1521

1622
return fexistsResolved(resolvedSpecifier);
1723
}

0 commit comments

Comments
 (0)