【发布时间】:2014-10-23 20:40:49
【问题描述】:
我有一个函数可以检查用户是否进行了任何更改,如果是,则警告他们这一事实。当他们选择放弃他们的更改时,我有另一个函数 a) 将状态恢复为预编辑,b) 更新一个全局对象,该对象包含有关当前编辑的信息(包括是否存在)。
我不想要发生的事情是尝试删除编辑框元素时引发了一些错误,因此系统不会更新全局对象标志或显示隐藏的预编辑元素。如果发生这种情况,程序可能会认为编辑仍在进行,而实际上并非如此,从而使用户陷入“放弃更改?”的困境。循环。出于这个原因,我捕获了销毁阶段抛出的任何错误,然后显示隐藏元素并更新全局,如下所示:
function cancelEdit() {
try {
// destroy editing boxes
// [code goes here]
} catch(e) {
} finally {
// restore hidden elements
// [code goes here]
// update global edit cache object
// [code goes here]
// rethrow the error for analysis server-side
if(window.onerror) window.onerror();
}
}
像上面那样有一个空的 catch 块对我来说似乎是一种代码味道,但我认为这种方式不一定更好。 (但也许是。)
function cancelEdit() {
try {
// destroy editing boxes
// [code goes here]
} catch(e) {
cancelEditInternal();
// rethrow the error for analysis server-side
throw e;
}
cancelEditInternal();
}
function cancelEditInternal() {
// restore hidden elements
// [code goes here]
// update global edit cache object
// [code goes here]
}
我错过了什么吗?有没有我忽略的模式......或者这只是我在通常不使用的地方使用 try/catch/finally 的结果?
【问题讨论】:
-
哎呀,我觉得我想多了。感谢您的快速回复。
标签: javascript try-catch-finally