简体   繁体   English

关于throw事件的Javascript?

[英]Javascript on throw event?

Is there a way in Javascript to listen to on throw events? 有没有办法在Javascript中收听投掷事件?

I want to be able to have an event handler be called even when code like this is executed: 我希望能够在执行这样的代码时调用事件处理程序:

var hi = "hi";
try {
  throw hi;
}
catch (e) {

}

In chrome (and maybe firebug too) you can run this code and hit "break on all errors" and it will break on that throw line. 在chrome(也可能是firebug)中,您可以运行此代码并点击“中断所有错误”,它将在该抛出线上中断。 How exactly are they doing that? 他们究竟是怎么做到的? Is that outside of Javascript? 那是Javascript之外的吗?

他们如何做到这一点是JavaScript引擎不会继续错误,它会在所有错误上崩溃,比如你编译c ++,它不是语言功能,它的浏览器

The answer you accepted is not correct. 你接受的答案是不正确的。

If you have an error that happens not within try {} catch() {} block, then the JavaScript execution will really break at that point. 如果你有一个错误发生在try {} catch() {}块中,那么JavaScript执行将在那时真正中断。

However, if you wrap your possibly breaking code in try {} catch() {} , you can use re- throw the error to be handled by one global event handler: 但是,如果在try {} catch() {}包装可能中断的代码,则可以使用重新throw错误来处理一个全局事件处理程序:

window.onerror = function (error) {
  // access `error` object
};

try {
  // for example try to assign property to non-existing object
  undefinedObj[property] = 1;
}
catch (error) {
  // `error` object will be available in `onerror` handler above
  throw new Error(error);
}

That's not event that's exception, the handler goes in the catch-block: 这不是异常事件,处理程序进入catch块:

try {
    //....
}
catch (e) {
    // exception handling here
    // or may be fire/trigger some event here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM