Error url is not useful for dynamically injected javascript functions. Need user supplied reference

StackOverflow https://stackoverflow.com/questions/7476781

  •  23-01-2021
  •  | 
  •  

Question

javascript which is introduced from a string instead of a .js file is difficult to debug because errors reference the url of the script file containing the error. If many strings are introduced, it is difficult to tell which string(script) is the source of the error.

I have a large number of objects. Each object has a string which will dynamically define its javascript functions. Once the functions have been defined, I need a way for errors that occur during the execution of these dynamically defined functions to report some kind of information that indicates which string/object is the source of the error.

EXAMPLE 1: Inject functions using eval()

If you use eval() to insert the string as javascript, the error url is undefined.

str = "test_fn = function(){undefined_fn();}";
eval(str);
test_fn();

will yield the following error:

message: "ReferenceError: Can't find variable: undefined_fn"
url: undefined
line: 1

So in this case, the error url is undefined.

EXAMPLE 2: Inject functions using a script tag

If instead of eval, you use a script tag to insert the string as javascript, the error url references the html file.

str = "test_fn = function(){undefined_fn();}";
if(!document.head) document.head = document.getElementsByTagName('head')[0];
var elem = document.createElement('script');
elem.text = str;
document.head.appendChild(elem);
test_fn();

will yield the following error:

message: "ReferenceError: Can't find variable: undefined_fn"
url: "testpage.html"
line: 1

So in this case, the error url is the html page.

I need a way for errors that occur during the execution of these dynamically defined functions to report to the developer some kind of information that indicates which string is the source of the error. I know that I could use the server to dynamically generate a large number of source files and then set script.src for each file, however I would like to avoid referencing hundreds of script files. I would rather prefer to understand how to perhaps modify the url that is reported, or pass some additional information that could be reported to the developer.

I would prefer a cross browser solution, but since this is for development only, it is not necessary.

Errors in these examples were reported using: window.onerror = function(message, url, line) {}

Was it helpful?

Solution

What about this:

function SuperError(msg, location) {
   this.message = msg;
   this.url = location;
}

str = "test_fn = function(){try { undefined_fn(); } catch(e) {throw new SuperError('undefined_fn is undefined', 'in dynamic script head')}}";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top