Skip to content

Commit 42999b2

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 1e83c51 commit 42999b2

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
@@ -27,7 +27,10 @@ export function selectedVersionCorrespondingURL(
2727
currentLocation,
2828
currentBaseURL}: CorrespondingURLParams
2929
): URL | undefined {
30-
const current_path = (new URL(currentBaseURL)).pathname
30+
const current_path = safeURLParse(currentBaseURL)?.pathname
31+
if (current_path === undefined) {
32+
return
33+
}
3134
const currentRelativePath = stripPrefix(currentLocation.pathname, current_path)
3235
if (currentRelativePath === undefined) {
3336
return
@@ -40,17 +43,37 @@ export function selectedVersionCorrespondingURL(
4043
return
4144
}
4245

43-
const potentialSitemapURL = new URL(currentRelativePath, sitemapCommonPrefix)
44-
if (!selectedVersionSitemap.has(potentialSitemapURL.href)) {
46+
const potentialSitemapURL = safeURLParse(currentRelativePath, sitemapCommonPrefix)
47+
if (!potentialSitemapURL || !selectedVersionSitemap.has(potentialSitemapURL.href)) {
4548
return
4649
}
4750

48-
const result = new URL(currentRelativePath, selectedVersionBaseURL)
51+
const result = safeURLParse(currentRelativePath, selectedVersionBaseURL)
52+
if (!result) {
53+
return
54+
}
4955
result.hash = currentLocation.hash
5056
result.search = currentLocation.search
5157
return result
5258
}
5359

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

5679
/**

0 commit comments

Comments
 (0)