Skip to content

Commit

Permalink
[WIP] Throw more useful errors
Browse files Browse the repository at this point in the history
  • Loading branch information
domoscargin committed Sep 5, 2023
1 parent b56cebf commit 49b3faa
Showing 1 changed file with 21 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,42 @@ export class SkipLink extends GOVUKFrontendComponent {
this.$module = $module

// Check for linked element
const $linkedElement = this.getLinkedElement()
if (!$linkedElement) {
throw new MissingElementError('The linked HTML element does not exist')
try {
const $linkedElement = this.getLinkedElement()
this.$linkedElement = $linkedElement
} catch (cause) {
const message = cause instanceof Error ? cause : new Error(String(cause))
throw new MissingElementError('The linked HTML element does not exist', {
message
})
}

this.$linkedElement = $linkedElement
this.$module.addEventListener('click', () => this.focusLinkedElement())
}

/**
* Get linked element
*
* @private
* @returns {HTMLElement | null} $linkedElement - DOM element linked to from the skip link
* @throws {Error} If the "href" attribute does not contain a hash
* @throws {Error} If the element with the specified ID does not exist
* @returns {HTMLElement} $linkedElement - DOM element linked to from the skip link
*/
getLinkedElement() {
const linkedElementId = this.getFragmentFromUrl()
if (!linkedElementId) {
return null
throw new Error(
`The Skip Link's "href" attribute does not contain a hash`
)
}

return document.getElementById(linkedElementId)
const linkedElement = document.getElementById(linkedElementId)

if (!linkedElement) {
throw new Error(`Element with ID "${linkedElementId}" does not exist`)
}

return linkedElement
}

/**
Expand Down

0 comments on commit 49b3faa

Please sign in to comment.