Skip to content

Commit 0b3cc93

Browse files
committed
Make sure selectedVersionCorrespondingURL never throws an exception
I polyfilled `URL.parse` since many browsers don't support it yet, apparently. I'd like this function to never throw an exception, any error should lead to it simply returning `undefined`.
1 parent cadc60e commit 0b3cc93

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

src/templates/assets/javascripts/integrations/version/correspondingPage.ts

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ export function selectedVersionCorrespondingURL(
2424
currentLocation,
2525
currentBaseURL}: CorrespondingURLParams
2626
): URL | undefined {
27-
const current_path = (new URL(currentBaseURL)).pathname
27+
const current_path = safeURLParse(currentBaseURL)?.pathname
28+
if (current_path === undefined) {
29+
return
30+
}
2831
const currentRelativePath = stripPrefix(currentLocation.pathname, current_path)
2932
if (currentRelativePath === undefined) {
3033
return
@@ -37,17 +40,37 @@ export function selectedVersionCorrespondingURL(
3740
return
3841
}
3942

40-
const potentialSitemapURL = new URL(currentRelativePath, sitemapCommonPrefix)
41-
if (!selectedVersionSitemap.has(potentialSitemapURL.href)) {
43+
const potentialSitemapURL = safeURLParse(currentRelativePath, sitemapCommonPrefix)
44+
if (!potentialSitemapURL || !selectedVersionSitemap.has(potentialSitemapURL.href)) {
4245
return
4346
}
4447

45-
const result = new URL(currentRelativePath, selectedVersionBaseURL)
48+
const result = safeURLParse(currentRelativePath, selectedVersionBaseURL)
49+
if (!result) {
50+
return
51+
}
4652
result.hash = currentLocation.hash
4753
result.search = currentLocation.search
4854
return result
4955
}
5056

57+
/**
58+
* A version of `new URL` that never throws. A polyfill for URL.parse() which is
59+
* not yet ubuquitous.
60+
*
61+
* @param url - passed to `new URL` constructor
62+
* @param base - passed to `new URL` constructor
63+
*
64+
* @returns `new URL(url, base)` or undefined if the URL is invalid.
65+
*/
66+
function safeURLParse(url: string|URL, base?: string|URL): URL | undefined {
67+
try {
68+
return new URL(url, base)
69+
} catch {
70+
return
71+
}
72+
}
73+
5174
// Basic string manipulation
5275

5376
/**

0 commit comments

Comments
 (0)