asutherland
asutherland

Reputation: 2969

Possible to set the "fileName" of an inline script tag that is displayed when errors occur?

If I have an inline script like whats below where the function foo is undefined, I want to be able to do something like:

<script fileName='foo.js'>
  foo();
</script>

and control what file name is displayed in the error console and/or to control what file name is passed to window.onerror when it handles the error. eg, I want to control the url param that gets sent to

window.onerror = function (errMsg, url, line) {
    console.log(url); //would like this to output 'foo.js'
    console.log(event.filename);  //would like this to also output 'foo.js'
}

By default, unless a script links to an external file only the parent html file is listed but it would be very nice to be able to have inline code in different script tags state which script tag an error originated from.

Is there any way to do this?

Upvotes: 0

Views: 405

Answers (1)

Casey Foster
Casey Foster

Reputation: 6020

As far as I know javascript is oblivious to the HTML tags it is run inside. Could something like this work for you?

<script>
  try {
    foo();
    // the rest of the code...
  } catch (err) {
    console.log('Caught error in foo.js');
    console.error(err);
  }
</script>

If you're adding these scripts dynamically to the page you should be able to wrap them with this try/catch code and get the desired effect.

Upvotes: 1

Related Questions