Skip to content

Commit

Permalink
Catch errors when modules initialised
Browse files Browse the repository at this point in the history
- wraps the initialisation of modules on a page with a try/catch block, so that if an error occurs in one module initialisation continues to the next without aborting and breaking all of the JS that follows
  • Loading branch information
andysellick committed Jan 16, 2023
1 parent d006ea8 commit 258d9cc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
9 changes: 7 additions & 2 deletions app/assets/javascripts/govuk_publishing_components/modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,13 @@
if (typeof GOVUK.Modules[moduleName] === 'function' && !started) {
// Vanilla JavaScript GOV.UK Modules and GOV.UK Frontend Modules
if (GOVUK.Modules[moduleName].prototype.init) {
new GOVUK.Modules[moduleName](element).init()
element.setAttribute('data-' + moduleNames[j] + '-module-started', true)
try {
new GOVUK.Modules[moduleName](element).init()
element.setAttribute('data-' + moduleNames[j] + '-module-started', true)
} catch (e) {
// if there's a problem with the module, don't start it
console.error('Error starting ' + moduleName + ' component JS: ' + e.message, window.location)
}
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions spec/javascripts/govuk_publishing_components/modules.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,16 @@ describe('GOVUK Modules', function () {
}
GOVUK.Modules.TestCookieDependencyModule = TestCookieDependencyModule

// module with a deliberate error in it
function TestErrorModule (element) {
this.element = element
}
TestErrorModule.prototype.init = function () {
throw new Error('This is a deliberate error')
callbackGemFrontendModule(this.element)
}
GOVUK.Modules.TestErrorModule = TestErrorModule

container = $('<div></div>')
})

Expand All @@ -129,6 +139,7 @@ describe('GOVUK Modules', function () {
delete GOVUK.Modules.GemTestAlertFrontendModule
delete GOVUK.Modules.TestAlertPublishingAndFrontendModule
delete GOVUK.Modules.TestCookieDependencyModule
delete GOVUK.Modules.TestErrorModule

container.remove()
})
Expand Down Expand Up @@ -209,5 +220,16 @@ describe('GOVUK Modules', function () {
window.GOVUK.triggerEvent(window, 'cookie-consent')
expect(callbackFrontendModule.calls.count()).toBe(2)
})

it('detects errors in modules and continues without failing', function () {
var module1 = $('<div data-module="test-error-module"></div>')
var module2 = $('<div data-module="gem-test-alert-frontend-module"></div>')
container.append(module1)
container.append(module2)
$('body').append(container)

GOVUK.modules.start(container[0])
expect(callbackGemFrontendModule.calls.count()).toBe(1)
})
})
})

0 comments on commit 258d9cc

Please sign in to comment.