error params are null in window.onerror in google chrome

Viewed 1806

I have html page which causes js error and an global handler for it.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
    <script type="text/javascript">
        $(function () {
            window.onerror = function (errorMsg, url, lineNumber) {
                alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber);
            }

            throw new Error("this is error");
        });
    </script>
</head>
<body>
    <div>Test page</div>
</body>
</html>

I receive alert: "Error: Script error. Script: Line: 0". As you can see error info is missing. How can I get this info here like I can see errors in developer tools. Any extensions for chrome are not suitable. I must catch errors with their info in javascript.

5 Answers

I am just adding answer for the sake of those who came here looking.

Source: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

Please go this URL, as you can see there are five parameters to

window.onerror = function(message, source, lineno, colno, error) { ... }

the last one is the one you need, it has complete record of what you see in console in case of error.

message: error message (string). Available as event (sic!) in HTML onerror="" handler.
source: URL of the script where the error was raised (string)
lineno: Line number where error was raised (number)
colno: Column number for the line where the error occurred (number)
error: Error Object (object)

Then Error Object has two properties

message
stack

stack is the one which will contain all the information you required.

Related