EN
JavaScript - get error line number, column number, message, stack, type, etc.
10
points
In this short article, we would like to show how to get error line number, column number, message, stack, type, etc. using JavaScript.
Quick solution:
Handle
window.onerrorevent at the source code beginning.
window.onerror = function(event, file, line, column, error) {
console.log('[FILE]: ' + file);
console.log('[LINE]: ' + line);
console.log('[COLUMN]: ' + column);
console.log('[TYPE]: ' + error.name);
console.log('[MESSAGE]: ' + error.message);
console.log('[STACK]:\n' + error.stack);
};
Practical example
Web browser JavaScript provides prcised details about occurred error location only when window.onerror event is used. In the below examples you can find 2 cases: unhandled exception, and syntax error.
Warning: the solution may be not working when files are run from file system, so it can be good to use some server to test examples locally.
Unhandled exception
// ONLINE-RUNNER:browser;
<html>
<head>
<script>
window.onerror = function(event, file, line, column, error) {
console.log('[FILE]: ' + file);
console.log('[LINE]: ' + line);
console.log('[COLUMN]: ' + column);
console.log('[TYPE]: ' + error.name);
console.log('[MESSAGE]: ' + error.message);
console.log('[STACK]:\n' + error.stack);
};
</script>
</head>
<body>
<script>
// ...
throw new Error('Some uncaught error ...');
// ...
</script>
</body>
</html>
Syntax error
// ONLINE-RUNNER:browser;
<html>
<head>
<script>
window.onerror = function(event, file, line, column, error) {
console.log('[FILE]: ' + file);
console.log('[LINE]: ' + line);
console.log('[COLUMN]: ' + column);
console.log('[TYPE]: ' + error.name);
console.log('[MESSAGE]: ' + error.message);
console.log('[STACK]:\n' + error.stack);
};
</script>
</head>
<body>
<script>
// ...
const action = %; // <--- Syntax error here ...
// ...
</script>
</body>
</html>
Internet Explorer
In this section, you can find legacy version that works also under Microsoft Internet Explorer.
window.onerror = function(event, file, line, column, error) {
if (error) {
console.log('[FILE]: ' + file);
console.log('[LINE]: ' + line);
console.log('[COLUMN]: ' + column);
console.log('[TYPE]: ' + error.name);
console.log('[MESSAGE]: ' + error.message);
console.log('[STACK]:\n' + error.stack);
} else {
// Microsoft IE:
console.log('[FILE]: ' + file);
console.log('[LINE]: ' + line);
console.log('[COLUMN]: ' + column);
console.log('[MESSAGE]: ' + event); // `event` argument is a message
// `error` argument is undefined
}
};