javascripterror-handlingline-numbersdynamic-script-loading

How can I get the line-number of an error in a dynamically added <script> tag?


When dynamically creating a script element and adding it to the page, my errors are not giving me line numbers of the script, but instead the line number where I append the script.

The code below when in a .js file will give you a line number error of whichever line document.appendChild(script) is on. The code snippet, if ran, will return the correct line number. How do they do this?

var script = document.createElement("script");
script.innerHTML = "\n\n\n\n\n\n\nfoo.bar";  //error should be on line 8

document.head.appendChild(script)


Solution

  • Got it. Adding a try catch around the code works great

    catchableScript = function(scriptText) {
        var scriptText = "try {\n"+scriptText+"\n} \n catch(ex){console.log(ex.lineNumber-1)}";
    
        var script = document.createElement("script");
        script.innerHTML = scriptText;
    
        document.head.appendChild(script)
    
    }
    
    catchableScript("\n\n\n\n\n\n\nfoo.bar");
    

    Output: 8

    Also, the exception has more information which is useful, but this is the answer to the question.

    EDIT:

    For those who want it, adding this code:

    window.CURRENTLY_EVALED_SCRIPT = scriptText;
    var scriptText = "try {\n"+scriptText
        +"\n} catch(ex){\n"
        +"var lineNumber = ex.lineNumber-1;\n"
        +"var errorOut = {};\n"
        +"errorOut.exception = ex;\n"
        +"errorOut.lines = window.CURRENTLY_EVALED_SCRIPT.split('\\n');\n"
        +"var line = errorOut.lines[lineNumber-1];\n"
        +"console.log(ex.message+' on line\\n'+line+' :: '+lineNumber, window.CURRENTLY_EVALED_SCRIPT_ELEMENT, errorOut);\n"
                +"}";
    
        ...
    
    window.CURRENTLY_EVALED_SCRIPT_ELEMENT = script
    

    Will result in this output in console:

    foo is not defined on line
    foo.bar :: 8, <script>, Object { exception: ReferenceError, lines: Array[8] }
    

    And you can click <script> to go to appended element, or lines to just see an array of all the lines.

    Works like a charm.