Skip to content

Instantly share code, notes, and snippets.

@wtnabe
Last active January 4, 2025 13:58
Show Gist options
  • Save wtnabe/cd32c7094e250c274255d00a902ee795 to your computer and use it in GitHub Desktop.
Save wtnabe/cd32c7094e250c274255d00a902ee795 to your computer and use it in GitHub Desktop.
JavaScriptでcallback functionの中で発生したエラーを外から捕捉する
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Promiseの中のエラーを拾う</title>
</head>
<body>
<button id="error-propagated-by-event">DOM Eventで伝播</button>
<button id="error-propagated-by-callback">Errorハンドラで伝播</button>
<script>
const btnEvent = document.getElementById('error-propagated-by-event')
btnEvent.addEventListener('click', (ev) => {
try {
clickHandlerWithDOM(ev.target)
} catch (e) {
console.error(['caught by try-catch', e])
}
})
btnEvent.addEventListener('error', (ev) => {
console.error(['caught by DOM Event', ev.detail])
})
function clickHandlerWithDOM (ele) {
processWithDOM(ele)
}
function processWithDOM (ele) {
setTimeout(() => {
try {
Foo
} catch (err) {
ele.dispatchEvent(new CustomEvent('error', { detail: err }))
}
}, 0)
}
//
const btnHandler = document.getElementById('error-propagated-by-callback')
btnHandler.addEventListener('click', (ev) => {
try {
clickHandlerWithCallback()
} catch (e) {
console.error(['caught by try-catch', e])
}
})
function clickHandlerWithCallback (e) {
processWithCallback(errorHandler)
}
function processWithCallback (handler) {
setTimeout(() => {
try {
Foo
} catch (err) {
handler(err)
}
}, 0)
}
function errorHandler (err) {
console.error(['caught by Handler callback', err])
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment