I'm using Rhino Script Engine and was wondering if it's possible (and how) to register a global handler that could be invoked whenever an unhandled exception is triggered.
I know that I cannot use browser objects like window
to register a handler with something like:
window.addEventListener("error", function (e) {
alert("Error occurred: " + e.error.message);
return false;
})
Is there an alternative?
Depending exactly what you want -- and exactly what you have -- here's one approach:
var setUncaughtExceptionHandler = function(f) {
Packages.org.mozilla.javascript.Context.getCurrentContext().setErrorReporter(
new JavaAdapter(
Packages.org.mozilla.javascript.ErrorReporter,
new function() {
var handle = function(type) {
return function(message,sourceName,line,lineSource,lineOffset) {
f({
type: type,
message: String(message),
sourceName: String(sourceName),
line: line,
lineSource: String(lineSource),
lineOffset: lineOffset
});
};
};
["warning","error","runtimeError"].forEach(function(name) {
this[name] = handle(name);
},this);
}
)
);
};
setUncaughtExceptionHandler(function(error) {
Packages.java.lang.System.err.println("Caught exception: " + JSON.stringify(error,void(0)," "));
});
var x = true;
var y = null;
var z = y.foo;
The output for this is:
Caught exception: {
"type": "error",
"message": "uncaught JavaScript runtime exception: TypeError: Cannot read property \"foo\" from null",
"sourceName": "null",
"line": 0,
"lineSource": "null",
"lineOffset": 0
}