WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 4ea3d71

Browse files
authored
Add setErrorHandler (#4673)
* Add `setErrorHandler` * Add test
1 parent 92a9fd0 commit 4ea3d71

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

packages/alpinejs/src/alpine.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { transition } from './directives/x-transition'
88
import { clone, cloneNode, skipDuringClone, onlyDuringClone, interceptClone } from './clone'
99
import { interceptor } from './interceptor'
1010
import { getBinding as bound, extractProp } from './utils/bind'
11+
import { setErrorHandler } from './utils/error'
1112
import { debounce } from './utils/debounce'
1213
import { throttle } from './utils/throttle'
1314
import { setStyles } from './utils/styles'
@@ -39,6 +40,7 @@ let Alpine = {
3940
onlyDuringClone,
4041
addRootSelector,
4142
addInitSelector,
43+
setErrorHandler,
4244
interceptClone,
4345
addScopeToNode,
4446
deferMutations,

packages/alpinejs/src/utils/error.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,17 @@ export function tryCatch(el, expression, callback, ...args) {
66
}
77
}
88

9-
export function handleError(error , el, expression = undefined) {
9+
export function handleError(...args) {
10+
return errorHandler(...args)
11+
}
12+
13+
let errorHandler = normalErrorHandler
14+
15+
export function setErrorHandler(handler) {
16+
errorHandler = handler
17+
}
18+
19+
export function normalErrorHandler(error , el, expression = undefined) {
1020
error = Object.assign(
1121
error ?? { message: 'No error message given.' },
1222
{ el, expression } )

tests/cypress/integration/error-handling.spec.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,3 +200,20 @@ test('evaluation with syntax error',
200200
assertConsoleInterceptorHadErrorWithCorrectElement(),
201201
true
202202
)
203+
204+
test('custom error handler',
205+
[html`
206+
<div id="custom">
207+
<div x-init="doesNotExist()"></div>
208+
</div>
209+
`,
210+
setupConsoleInterceptor( "custom" ) + `
211+
Alpine.setErrorHandler((error, el) => {
212+
// Report parent element instead
213+
console.warn(error, el.parentNode)
214+
})
215+
`,
216+
],
217+
assertConsoleInterceptorHadErrorWithCorrectElement(),
218+
true
219+
)

0 commit comments

Comments
 (0)