Is it possible to get the local variable and parameter values with window.onerror

#1 Can local scope be recovered in onerror() without black magic?

Without this being bound in the scope of window.onerror() or the surrounding variables being directly accessible, it's impossible to regain access to the variables you had set.

What you're mostly wanting access to is this.arguments or arguments or the equivalent, but that's destroyed. Any hope of obtaining a key-value associative array or hash-like object would involve meta-programming ( i.e. reading the function definition to obtain the variable names, and obtaining an exception report to attempt to salvage data ).

See this answer for more on something similar:

  • Getting All Variables In Scope

But this "lacking functionality" is a good thing:

If you could gain access to what you're asking for, that would likely be a fault in the Javascript engine. Why? Because the variable states and contents themselves are what caused the exception/error, assuming bad code wasn't the issue to begin with.

In other words, if you could get access to a faulty variable, that might be a door into an infinite loop:

  1. Failure due to variable contents.
  2. Error handler triggered.
  3. Trace contents of variable.
  4. Failure due to variable contents.
  5. Error handler triggered.
  6. Trace contents of variable.
  7. Etc.

#2 Can Javascript store all arguments of every function call by voodoo?

Yes. It can. This is probably a really bad idea ( see #1 ) but it is possible. Here is a pointer on where to start:

  • Is there a way to wrap all JavaScript methods with a function?

From there, what you're wanting to do is push this.arguments or equivalent to a stack of function calls. But again, this is approaching insanity for many reasons. Not the least of which is the need to duplicate all the values, lest you reference mutated variables, or be unable to access the data at all... and like I said above, the problem of bad data in general. But still, it is possible.


Is this even possible?

No. A stack trace is proof that the stack has unwound, all stack frames and all the local variables they contained are gone. As for getting the name of a variable, that is not even possible at run time.


To start off i accept @Tomalak completely.

I was also put in your situation where i needed to debug a remote running app in case of crash.

As a work around I have forked my code for you in a fiddler. Please modify according to your need.

Caveat: You have to wrap the function body with try{..}catch(e){..} as illustrated in the fiddler code.

Please read the inline comments for understanding.

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {       
        console.log(errorObj);
}

window.addEventListener("reportOnError", function(e){   
    console.log(e.detail);    
  /*Send to the server or any listeners for analysis.*/  
  //Http.send(e.detail);  
});

function ExceptionReport(ex, args, scope) {
    var self = {};
   self.message = ex.message;
   self.stack = ex.stack;
   self.name = ex.name;
   self.whoCalled = args.callee.caller.name == "" ? "Window": args.callee.caller.name;
   self.errorInFunction = args.callee.name;
   self.instanceOf = scope.constructor;
   self.KeyPairValues = getParamNames(arguments.callee.caller.toString(), Array.prototype.slice.call(args)); //Contains the parameters value set during runtime
   window.dispatchEvent(new CustomEvent('reportOnError', {'detail':self}));
}

//Utilties 
function getParamNames(fnBody, values) {
  var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
        ARGUMENT_NAMES = /([^\s,]+)/g,
        result = fnBody.slice(fnBody.indexOf('(')+1, fnBody.indexOf(')')).match(ARGUMENT_NAMES),
        obj={};

  fnBody.replace(STRIP_COMMENTS, '');  
  if(result !== null){      
        for(var i=0; i < result.length; i++){
        obj[result[i]] = values.length !==0 ? values[i] : null;
      }    
  }else{
    obj = null;
  }  
  return obj;
}

/*
    This is a testing/sample function that throws the error
*/
function testing(a,b,c){
    try{  
        dummy(1,2) ; //This line throws the error as reference error.
  }catch(e){    
        ExceptionReport(e, arguments, this);
  }
}

//Class Emulation: For instanceof illustration.
function testingClass(){
    this.testing = testing;
}

//Named self executing function: This calls the function
var myvar = (function myvar(){
    testing(1,2,3);
})();

//Illustrating instanceof in exception 
var myVar2 = new testingClass();
myVar2.testing(1,2,3);

//Calling from global scope this is Window
testing(1,2,3);

//Without variables
testing();

I have used examples to illustrate the behavior of functions called in different circumstances.

Below signifies the varialble used for

  • self.KeyPairValues : Used to store the function parameter set/passed during runtime
  • self.errorInFunction : This stores the name of the function error was caused in.
  • self.whoCalled : This stores the function name that invoked the defective function
  • self.instanceOf : This stores the name of the instance is called creating a new instance.

Other variables are same as in Error object