How do I make sure all JavaScript errors are written to the Chrome Developer Tools Console?
-
26-10-2019 - |
Question
Consider the following JavaScript function:
function triggerError() {
var something = undefined;
// The next line will trigger 'TypeError: Cannot call ... of undefined'
something.doesNotExist();
}
When running triggerError();
directly the following error is written to the Chrome Developer Tools Console in red, which is expected:
TypeError: Cannot call method 'doesNotExist' of undefined
However, when triggerError();
is being run from an event listener no errors are written to the console (the function call just silently dies at something.doesNotExist();
) which makes things quite tricky to debug in case of typos, etc.
How do I make sure all errors are written to the Chrome Developer Tools Console, including errors generated in code which is being run from event listeners/callbacks?
One obvious work-around would be to add try { ... } catch (x) { console.log(x) };
all over the place, but since I don't know beforehand where I'll be adding typos this is not a way forward.
Solution
Could you show your sample, I tried to reproduce it on the following snippet and it works perfectly fine for me:
<script>
function triggerError() {
var something = undefined;
// The next line will trigger 'TypeError: Cannot call ... of undefined'
something.doesNotExist();
}
window.addEventListener("click", triggerError, true);
</script>
<body onclick="triggerError()">
</body>
OTHER TIPS
You could use a try catch
:
function triggerError() {
try{
var something = undefined;
// The next line will trigger 'TypeError: Cannot call ... of undefined'
something.doesNotExist();
}catch(ex){
console.error(ex.message);
}
}