代码之家  ›  专栏  ›  技术社区  ›  Chris Barry

在try-catch块中未捕获Asp.net MVC异常

  •  0
  • Chris Barry  · 技术社区  · 16 年前

    所有代码的工作原理都类似于书呆子晚餐。

    NounRepository nounRepository = new NounRepository();
            Noun noun = new Noun();
            try
            {                
                UpdateModel(noun);
                nounRepository.Add(noun);
                nounRepository.save();
            }
            catch (Exception ex)
            {
                ModelState.AddRuleViolations(noun.GetRuleViolations());
                return View(noun);
            }
        return View(noun);
    

    更新

    UpdateModel(noun);
    
                if (!noun.IsValid)
                {
    
                    var errors = noun.GetRuleViolations();
                    ModelState.AddRuleViolations(noun.GetRuleViolations());
                    return View(noun);
    
                }
    
                nounRepository.Add(noun);
                nounRepository.save();
    

    我不希望以这种方式添加代码,因为这似乎是不必要的重复。

    3 回复  |  直到 16 年前
        1
  •  1
  •   st78    16 年前

    您在mvc中遇到了逻辑变化——这里的验证不抛出异常。实际上,您需要使用if语句来检查它。

    我怀疑是否发生了异常-无论如何,您都需要捕获linq2sql异常,因为代码是正确的。此外,在“保存”或“添加”中,您很有可能会遇到另一个陷阱——这是一个非常常见的错误

        2
  •  1
  •   Aaronaught    16 年前

    编程规则#1: catch 没有坏(又名: SELECT 没有坏)。

    如果您确实有疑问,请打开“调试”菜单,选择“异常”,然后在“抛出”下的“公共语言运行时异常”框中打勾。这将导致调试器在所有第一次出现异常时中断。如果调试器在更新过程中没有中断,那么从一开始就不会抛出异常。

    附笔。 永远抓不到 System.Exception 捕获您知道可能实际引发的特定类型的异常。

        3
  •  0
  •   Daniel Auger    16 年前

    你在另一个线程中做什么?这通常是无法捕获异常的原因。

    推荐文章