-
Notifications
You must be signed in to change notification settings - Fork 174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: wrap Intl.<>() calls in try/catch #297
Conversation
src/relative-time-element.ts
Outdated
let dateTimeFormat | ||
try { | ||
dateTimeFormat = new Intl.DateTimeFormat(this.#lang, { | ||
day: 'numeric', | ||
month: 'short', | ||
year: 'numeric', | ||
hour: 'numeric', | ||
minute: '2-digit', | ||
timeZoneName: 'short', | ||
}) | ||
} catch (_e) { | ||
dateTimeFormat = new Intl.DateTimeFormat('default', { | ||
day: 'numeric', | ||
month: 'short', | ||
year: 'numeric', | ||
hour: 'numeric', | ||
minute: '2-digit', | ||
timeZoneName: 'short', | ||
}) | ||
} | ||
return dateTimeFormat.format(date) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@keithamus I did some research on using an array in the constructor instead but it'd fail anyways if one of the locales was invalid, so I settled on this.
Also I'm not quite sure how to test this but happy to update on Primer and test once this is in
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of try/catching each of the Intl
calls we could add a try/catch into #lang
:
get #lang() {
const lang = this.closest('[lang]')?.getAttribute('lang') ||
this.ownerDocument.documentElement.getAttribute('lang')
try {
return new Intl.Locale(lang).toString()
} catch {
return 'default'
}
}
This way #lang
would always return a reliable language code and we minimise the surface area of changes.
@keithamus done in 0a42e68, much better now, thanks! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM, some tests might be interesting. Also you’ll need someone from Primer to approve as I am no longer in the reviewers team 🥹
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Overall LGTM, one nit:
Co-authored-by: Keith Cirkel <[email protected]>
Closes https://github.com/github/primer/issues/4409
Fixes error thrown when an invalid locale is passed to the
Intl
functions by wrapping it in Try/Catch. When the call fails (locale is invalid), the default locale will be used