我正在使用Rhino脚本引擎,想知道是否有可能(以及如何)注册一个全局处理程序,只要触发未处理的异常就会调用该全局处理程序。
我知道我无法使用window
之类的浏览器对象来注册具有以下内容的处理程序:
window.addEventListener("error", function (e) {
alert("Error occurred: " + e.error.message);
return false;
})
还有其他选择吗?
答案 0 :(得分:1)
准确地 想要的东西-确切地拥有什么-这是一种方法:
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;
此输出为:
Caught exception: {
"type": "error",
"message": "uncaught JavaScript runtime exception: TypeError: Cannot read property \"foo\" from null",
"sourceName": "null",
"line": 0,
"lineSource": "null",
"lineOffset": 0
}