0

Is it possible to give a name to code that I execute using eval?

When the browser loads a file and executes it, and then the code throws an exception, the browser can tell me in which file at which line the exception happened.

I want that it also can tell me where and in which evaled code an exception happened. It should display the name I gave this code then.

Hope you understand what I want.

Thanks for your help!

pimvdb
  • 151,816
  • 78
  • 307
  • 352
Van Coding
  • 24,244
  • 24
  • 88
  • 132
  • 4
    If you post some of the code, people may be able to help you find a way to do what you need to do without using "eval()" at all. That would be a much better outcome :-) – Pointy May 20 '11 at 15:59
  • Article "Why using eval() is a bad idea" :) http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea and a workaround for not using it: http://www.go4expert.com/forums/showthread.php?t=13979 – Scherbius.com May 20 '11 at 16:01
  • Trust me, it's not possible without eval. It's not what I'm asking for at all. Hope there is something I can do. – Van Coding May 20 '11 at 16:01
  • @FlashFan well there's no facility to do what you ask. – Pointy May 20 '11 at 16:05
  • @FlashFan: Can you post an example? I'm not sure what you mean by "name you gave that code then". – Piskvor left the building May 20 '11 at 16:07
  • Other question: is there a way to load & execute a script SYNCHRONOUSLY? – Van Coding May 20 '11 at 16:07
  • @FlashFan: If you have a completely different question, click the "Ask Question" (top right of page) and ask it as a question :) It's unlikely you'll get a useful response in the comments. – Piskvor left the building May 20 '11 at 16:08

1 Answers1

1

Assign your name to a local var right before executing the eval and then wrap the eval in a try/catch. In the catch, you'll have both the name and the exception.

function evalCode(name, code) {
  try {
    eval(code);
  } catch (e) {
    console.log('Error in ' + name + ':');
    console.log(code);
    throw e;
  }
}

You can't get the browser to tell you which line in the eval'd code contains the problem, as the code is treated as one distinct unit, but you can log both the name of the problem code and the problem code itself, as noted above.

quasistoic
  • 4,657
  • 1
  • 17
  • 10
  • This is an idea for code, that is executed synchronously, but what's about code, that is stored in a function and called later (throug an event) There is no way to catch those exceptions... – Van Coding May 20 '11 at 16:11
  • Wherever you're storing the string of code, you can also store a name. Wherever you're calling eval(), you can wrap it in a try/catch. – quasistoic May 20 '11 at 16:16
  • Edited for a little extra clarity. If this doesn't answer your question, could you be more specific about what you're trying to do and include code snippets, please? – quasistoic May 20 '11 at 17:09