您如何冒泡错误,以便可以将它们捕获在同一try/catch块中? [英] How can you bubble up errors so they can be caught in the same try/catch block?
问题描述
我有一个带有引发错误的函数的对象,
I've got an object with functions that throw errors,
myObj = {
ini:function(){
this.f();
},
f:function(){
throw new Error();
}
};
但是我只想在创建对象的地方捕获异常
but I only want to catch the exceptions where the object is created
try{
var o = new myObj();
}catch(err){
alert("error!");
}
看来我必须到处都有try/catch块=/才能捕获不同功能范围内的错误事件
it looks like i have to have try/catch blocks everywhere =/ to capture the error event in different function scopes
try{
myObj = {
ini:function(){
try{
this.f();
}catch(err){
alert("f threw an err");
}
},
f:function(){
throw new Error();
}
};
}catch(err){
alert("error happend while crating Obj");
}
但是我只想从一个地方捕获=/我该怎么做?
But I only want to capture from one place =/ How do I do this?
推荐答案
让您的函数抛出特定类型的对象,然后在catch块中检查 if(err instanceof MyExceptionObj)
和适当处理,否则将其扔掉.
Have your function throw a specific type of object, and then in your catch block check to see if (err instanceof MyExceptionObj)
and handle appropriately, otherwise re-throw it.
通过重新抛出,我的意思是:
By re-throw I mean:
如果捕获的异常对象不是您可以处理的对象,则应重新抛出该对象,以使任何捕获块都有进一步的机会来处理它.如果不执行任何操作,浏览器将捕获该错误并显示JS错误.
If the caught exception object isn't one you can handle, you should re-throw it to give any catch blocks further up a chance to handle it. If none do, the browser will catch it and display a JS error.
try {
if ($.browser.msie) {
throw new UnsupportedBrowserException();
}
} catch (ex) {
if (ex instanceof UnsupportedBrowserException) {
alert('Your browser isn't supported.');
} else {
// We don't know how to handle this exception, throw it back.
throw ex;
}
}
在现实世界中,您可能不会这样做.
You probably wouldn't do this in the real world.
这篇关于您如何冒泡错误,以便可以将它们捕获在同一try/catch块中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!