【问题标题】:How to handle exceptions in MVVM View Model properties ?如何处理 MVVM 视图模型属性中的异常?
【发布时间】:2013-10-21 16:30:11
【问题描述】:

当我的 ViewModel 中的属性发生时,我该如何处理发生的异常?该属性在 Loaded 事件之前发生。例如,我有一个属性(仅获取),它调用一些数据方法来返回状态集合以填充组合框的 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
}

【问题讨论】:

    标签: c# wpf exception properties getter


    【解决方案1】:

    让所有五个语句在 1 个 try catch 中连续使用,而不是对每个语句进行 try catch,因此如果发生异常,则 3 之后的第二个语句将不会被执行,并且不惜一切代价您将只有 1 个 msg 框,您可以返回主屏幕也没有任何问题

    【讨论】:

      【解决方案2】:

      这是您可以处理的一种方法..

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

      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..
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 2013-10-30
        • 2011-02-11
        • 2017-12-10
        • 2021-06-04
        • 2019-07-01
        • 1970-01-01
        相关资源
        最近更新 更多