Reputation: 3713
My question is simple, but Javascript VM dependent.
When catching a ReferenceError (in my case when doing eval(...)), how do I get back the actual identifier token from the error object?
Matching for "known" error messages and parsing them seems way too hackish for me, but is the only available option to me right now.
edit: For the moment I'm only "matching" V8 and Firefox by doing this:
catch(e){
if (e.name === "ReferenceError"){
var varname = e.toString().replace("ReferenceError: ","")
.replace(" is not defined","").trim();
foobar(varname);
}
}
Upvotes: 1
Views: 352
Reputation: 39542
You should be able to do this using e.message
and matching the text up until the first space.
The following code works in IE7/IE8/IE9/IE10/Chrome and Firefox.
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.substr(0, e.message.indexOf(" "));
//IE7 and IE8 fix (it adds ' around the variable name)
if (variableName.substr(0, 1) == "'" && variableName.substr(variableName.length - 1) == "'") {
variableName = variableName.substr(1, variableName.length - 2);
}
console.log(variableName); //tesssst
}
}
Edit:
Added IE7/IE8 fixes
Edit 2:
With a little regex magic you can change this to the following:
try {
alert(tesssst);
} catch(e){
if (e.name === "ReferenceError" || e.name === "TypeError") { //IE7 uses TypeError instead
var variableName = e.message.match(/^'?(.*?)'? /)[1];
console.log(variableName);
}
}
Upvotes: 1