Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/alpinejs/src/alpine.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { transition } from './directives/x-transition'
import { clone, cloneNode, skipDuringClone, onlyDuringClone, interceptClone } from './clone'
import { interceptor } from './interceptor'
import { getBinding as bound, extractProp } from './utils/bind'
import { setErrorHandler } from './utils/error'
import { debounce } from './utils/debounce'
import { throttle } from './utils/throttle'
import { setStyles } from './utils/styles'
Expand Down Expand Up @@ -39,6 +40,7 @@ let Alpine = {
onlyDuringClone,
addRootSelector,
addInitSelector,
setErrorHandler,
interceptClone,
addScopeToNode,
deferMutations,
Expand Down
12 changes: 11 additions & 1 deletion packages/alpinejs/src/utils/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ export function tryCatch(el, expression, callback, ...args) {
}
}

export function handleError(error , el, expression = undefined) {
export function handleError(...args) {
return errorHandler(...args)
}

let errorHandler = normalErrorHandler

export function setErrorHandler(handler) {
errorHandler = handler
}

export function normalErrorHandler(error , el, expression = undefined) {
error = Object.assign(
error ?? { message: 'No error message given.' },
{ el, expression } )
Expand Down
17 changes: 17 additions & 0 deletions tests/cypress/integration/error-handling.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,20 @@ test('evaluation with syntax error',
assertConsoleInterceptorHadErrorWithCorrectElement(),
true
)

test('custom error handler',
[html`
<div id="custom">
<div x-init="doesNotExist()"></div>
</div>
`,
setupConsoleInterceptor( "custom" ) + `
Alpine.setErrorHandler((error, el) => {
// Report parent element instead
console.warn(error, el.parentNode)
})
`,
],
assertConsoleInterceptorHadErrorWithCorrectElement(),
true
)