处理异常,错误讨论和解释

时间:2014-01-20 15:24:02

标签: c# asp.net-mvc exception exception-handling error-handling

我已阅读有关例外错误错误代码等各种主题。 我通过stackoverflow的问题搜索了一个答案,但我仍然有一些误解...... 因此,在阅读我的问题时,请让我们更多地考虑为客户提供更好的结果,而不是遵循可能在真实生活场景中无效的“理论”模式。让我们走吧:

一些规范,为我们的情况增加透明度:

  1. 3个图层(DataAccess - >服务 - > UI)
  2. 存储库模式
  3. ORM - NHibernate
  4. IoC - Castle Windsor
  5. 用户界面框架 - ASP.NET MVC3
  6. 情景:

    假设我们有一个服务接口:

    public interface IProductService
    {
        // Just get the products from DB
        IList<Products> GetAllProducts();
    
        // Makes a conversion between product's current UM and requested 'toUnitMeasure'
        double ConvertUnitMeasureTo(Product product, UnitMeasure toUnitMeasure);
    }
    

    现在让我们分析两种方法可能发生的事情:

    1. GetAllProducts();

      • 结果列表可能为空。
      • 数据库可能会抛出SqlException
    2. ConvertUnitMeasureTo(Product product, UnitMeasure toUnitMeasure);

      • 可能无法在数据库中找到product
      • 也可能找不到toUnitMeasure
      • product当前的单位指标可能无法转换为toUnitMeasure(例如:MASS到LENGTH)
      • 某种ArithmeticException等。
    3. 好到目前为止一切顺利。让我们来看看控制器:

      [HttpPost]
      public ActionResult Index(ProductViewModel model) 
      {
          if(ModelState.IsValid)
          {
              // At this point, some of the (above enumerated) situations may occur.
              // Some of them are Exceptions while another
              // are unpleasant but 'expected' situations.
              var result = _productService.ConvertToUnitMeasure(model.Product, model.UnitMeasure);
          }
      }
      

      问题:

      如何处理Controller内的所有情况?而:

      • 向客户端发送(本地化)答案。(例如:在CustomException.Message内对消息进行硬编码,不适合我的情况)
      • 能够区分可能发生的每种情况,以便采取特定的行动(例如:如果The toUnitMeasure might be not found either.制作RedirectToAction("CreateUnitMeasure","UnitMeasure"));
      • 尽可能保持Controller'瘦身'。例如:通过将Controller分隔为更小的服务方法,避免在ConvertUnitMeasureTo(..)内部而不是服务层中实施转换方法。 (希望不需要解释)

      您的回答对我有价值,所以请不要犹豫,表达自己。非常感谢您的关注。

0 个答案:

没有答案