window" /> window" /> window"/>

Why does throwing an error in any browser developer console not get caught by window.addEventListener('error')?

31 views Asked by At

Given this HTML document run using npx serve:

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>

<h1>Hello world</h1>

<script type="text/javascript">
    window.addEventListener('error', error => {
        console.log('DEBUG', 'error captured', error)
    })

    throw new Error('Caught by event listener!')
</script>
</body>
</html>

This will output in the developer console Debug error captured ErrorEvent { message: 'Uncaught Error. Caught by event listener!' }.

Console input Console output
const s = document.createElement('script'); s.text = 'throw new Error("This is caught")'; document.getElementsByTagName('head')[0].appendChild(s); Debug error captured ErrorEvent { message: 'Uncaught Error. This is caught!' }
window.dispatchEvent(new ErrorEvent('error', { message: 'This is caught' })) Debug error captured ErrorEvent { message: 'This is caught!' }
throw new Error('not caught') None

Why does throw new Error('not caught') in a browser console not dispatch an error event to then trigger the window.addEventListener('error')?

1

There are 1 answers

1
Victoria Hill On BEST ANSWER

When you throw an error directly in the browser's console, it doesn't bubble through the DOM or the javascript execution context that window.addEventListener('error', ...) listens to. This handler catches errors from scripts within the page's execution context. Thrown errors in the console are interpreted and handled by the console itself, separate from the webpage's script execution environment. Essentially, console errors stay in the console, and script errors get handled by script error handlers like the one you've set up.