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.onerror
event at the source code beginning.
xxxxxxxxxx
1
window.onerror = function(event, file, line, column, error) {
2
console.log('[FILE]: ' + file);
3
console.log('[LINE]: ' + line);
4
console.log('[COLUMN]: ' + column);
5
console.log('[TYPE]: ' + error.name);
6
console.log('[MESSAGE]: ' + error.message);
7
console.log('[STACK]:\n' + error.stack);
8
};
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.
xxxxxxxxxx
1
<html>
2
<head>
3
<script>
4
5
window.onerror = function(event, file, line, column, error) {
6
console.log('[FILE]: ' + file);
7
console.log('[LINE]: ' + line);
8
console.log('[COLUMN]: ' + column);
9
console.log('[TYPE]: ' + error.name);
10
console.log('[MESSAGE]: ' + error.message);
11
console.log('[STACK]:\n' + error.stack);
12
};
13
14
</script>
15
</head>
16
<body>
17
<script>
18
19
// ...
20
21
throw new Error('Some uncaught error ...');
22
23
// ...
24
25
</script>
26
</body>
27
</html>
xxxxxxxxxx
1
<html>
2
<head>
3
<script>
4
5
window.onerror = function(event, file, line, column, error) {
6
console.log('[FILE]: ' + file);
7
console.log('[LINE]: ' + line);
8
console.log('[COLUMN]: ' + column);
9
console.log('[TYPE]: ' + error.name);
10
console.log('[MESSAGE]: ' + error.message);
11
console.log('[STACK]:\n' + error.stack);
12
};
13
14
</script>
15
</head>
16
<body>
17
<script>
18
19
// ...
20
21
const action = %; // <--- Syntax error here ...
22
23
// ...
24
25
</script>
26
</body>
27
</html>
In this section, you can find legacy version that works also under Microsoft Internet Explorer.
xxxxxxxxxx
1
window.onerror = function(event, file, line, column, error) {
2
if (error) {
3
console.log('[FILE]: ' + file);
4
console.log('[LINE]: ' + line);
5
console.log('[COLUMN]: ' + column);
6
console.log('[TYPE]: ' + error.name);
7
console.log('[MESSAGE]: ' + error.message);
8
console.log('[STACK]:\n' + error.stack);
9
} else {
10
// Microsoft IE:
11
console.log('[FILE]: ' + file);
12
console.log('[LINE]: ' + line);
13
console.log('[COLUMN]: ' + column);
14
console.log('[MESSAGE]: ' + event); // `event` argument is a message
15
// `error` argument is undefined
16
}
17
};