如何处理 MVVM 视图模型属性中的异常

本文关键字:属性 模型 异常 视图 MVVM 何处理 处理 | 更新日期: 2023-09-27 18:36:12

如何处理 ViewModel 中的属性发生时发生的异常? 该属性在 Loaded 事件之前发生。 例如,我有一个属性(get-only),它调用某个数据方法来返回状态集合以填充组合框的 itemsource。 但有时SQL无法连接,我得到了一个解释。 有多个这样的属性,我想告诉用户组合无法正确加载,然后将它们放回我的主屏幕。 但是,如果它们都失败了,我不想要 5 个消息框。 另外,为什么它继续尝试获取属性,即使我告诉它在发生第一个异常时转到主屏幕? 注意:GetStatesList() 方法也有 try/catch 和 throw in the catch...

try
{
ObservableCollection<string> states=null;
// perform sql query
states=StateDat.Instance.GetStatesList();  //get the collection of state names
}
catch(Exception ex)
{
MessageBox.Show("Error");  //display an error message
MessengerInstance.Send(ViewModelNamesEnum.HomeVM);  //go home
}

如何处理 MVVM 视图模型属性中的异常

将所有五个语句连续使用 1 try catch,

而不是为每个语句进行 try catch,因此如果发生异常,3 之后的第二个语句将不会执行,并且无论如何您只有 1 个 msg 框,您也可以返回主屏幕,没有任何 issuse

这是您可以处理此问题的一种方法。

为每个属性调用创建单独的方法..并抛出自定义异常以指示该特定调用出现问题。无论如何,外部例外将确保如果一个失败,它会纾困。

Method1() {
 try { 
     //Code for Method1 
     }catch(Exception ex) { throw new CustomException(""); }
}
Method2() {
 try { 
     //Code for Method2 
     }catch(Exception ex) { throw new CustomException(""); }
}
Method3() {
 try { 
     //Code for Method3 
     }catch(Exception ex) { throw new CustomException(""); }
}

try {
    Method1();
    Method2();
    Method3();
}catch(CustomException custom) {
 // You would know specific reasons for crashing.. and can return meaningful message to UI.
 } catch(Exception ex) { 
 //Anything that was un-handled
}

class CustomException : Exception {
 //Implementation here..
}