【问题标题】:How to Error Handle a NullReferenceException如何错误处理 NullReferenceException
【发布时间】:2015-10-31 01:28:57
【问题描述】:

我的网站宕机了几天,因此我试图在 MVC 应用程序无法访问某些资源的情况下进行一些错误处理,因此如果某些东西不再不可用,整个事情都不必关闭。

此时控制器正试图访问不可用的 viewbag.moreNewProducts。

public ActionResult Index(string search)
    {
        string[] newProductLines = this.getMoreNewProducts();
        string[] newNews = this.getMoreNews();
        string[] newPromotions = this.getMorePromotions();
        string[] fewerProductLines = this.getLessNewProducts(newProductLines);
        ViewBag.moreNewProducts = newProductLines;
        ViewBag.moreNews = newNews;
        ViewBag.morePromotions = newPromotions;
        ViewBag.lessNewProducts = fewerProductLines;
        bool disableShowMore = false;

这是我遇到错误的地方:“foreach(newProductLines 中的字符串行)”

public string[] getLessNewProducts(string[] newProductLines)
    {
        int charCount = 0;
        int arrayCount = 0;
        string[] displayProductLines = new string[6];
        bool continueWriting;

            if (newProductLines == null)
            {

                foreach (string line in newProductLines)
                {
                    continueWriting = false;
                    for (int i = 0; charCount < 250 && i < line.Length && arrayCount < 5; i++)
                    {
                        string index = newProductLines[arrayCount].Substring(i, 1);
                        displayProductLines[arrayCount] += index;
                        charCount++;
                        continueWriting = true;
                    }
                    if (continueWriting == true)
                    {
                        arrayCount++;
                    }
                }
                string[] LessNewProducts = new string[arrayCount];
                for (int d = 0; d < arrayCount; d++)
                {
                    LessNewProducts[d] = displayProductLines[d];
                }
                return LessNewProducts;

            }

            else
            {
                return null;
            }




    }

我如何绕过 if else 语句,这样整个事情就不会崩溃?

【问题讨论】:

  • 您是否尝试将其包装在 try and catch 中?

标签: asp.net-mvc-4 error-handling nullreferenceexception


【解决方案1】:

真正要问自己的问题是:

为什么newProductLines 会为空?

大概getMoreNewProducts() 发现了一种情况,它认为返回null 值是合适的。

如果发生这种情况是因为系统有一个错误会使您的页面变得毫无意义,那么您可能只想更改getMoreNewProducts(),以便在该错误状态发生时引发异常。通常,调试一旦遇到意外情况就失败的程序是最安全和最容易的。

如果发生这种情况是因为没有新产品,那么您应该只返回一个空集合,而不是 null。此后,您的所有代码都应该可以正常工作,而无需 if/else 语句:它将为 LessNewProducts 返回一个空数组,这可能是正确的。

但是,让我们假设您预计会不时发生一种情况,这将使您当时无法检索newProductLines,但您希望系统能够正常处理.您可以只使用null 来表示该值不存在,但很难知道哪些变量可能为空,哪些永远不应该为空。使用an optional type 表示getMoreNewProducts() 可能根本不返回任何东西可能更明智,因此您可以强制任何使用代码来识别这种可能性,并在项目编译之前弄清楚如何处理它:

public ActionResult Index(string search)
{
    Maybe<string[]> newProductLines = this.getMoreNewProducts();
    string[] newNews = this.getMoreNews();
    string[] newPromotions = this.getMorePromotions();
    Maybe<string[]> fewerProductLines = newProductLines.Select(this.getLessNewProducts);

免责声明:我是上述Maybe&lt;&gt; 类的作者。

以下是我建议的一些额外改进:

  1. 不要使用 ViewBag。相反,创建一个强类型的 ViewModel 以便您可以在编译时更频繁地捕获代码中的错误:

    var viewModel = new ReportModel {
        newProductLines = this.getMoreNewProducts(),
        newNews = this.getMoreNews(),
        ...
    };
    ...
    return View(viewModel);
    
  2. 学习使用 LINQ。它将简化很多非常复杂的代码。例如,而不是:

            string[] LessNewProducts = new string[arrayCount];
            for (int d = 0; d < arrayCount; d++)
            {
                LessNewProducts[d] = displayProductLines[d];
            }
            return LessNewProducts;
    

    ...你可以说:

            string[] LessNewProducts = displayProductLines.Take(arrayCount).ToArray();
    

    其实我觉得你的整个getLessNewProducts()方法可以用这个代替:

    return newProductLines
        .Where(line => line.Length > 0)
        .Select(line => line.Substring(0, Math.Min(line.Length, 250)))
        .Take(5);
    

【讨论】:

    【解决方案2】:

    如果 (newProductLines == null)

    应替换为 if (newProductLines != null),这样您就不必处理 newProductLines 为 null 的代码。基本上,在这种情况下,除非您使用 try catch 块管理异常,否则您将始终遇到 NullReferenceException。

    【讨论】:

      【解决方案3】:

      两件事。

      1. 您的if (newProductLines == null) 语句的条件错误。如果newProductLines 为空,我不相信您想输入它。您可以反转此条件以获得所需的结果(if (newProductLines != null))。

      1. 如果以后遇到需要捕获错误的另一种情况,您始终可以使用 try-catch 块来捕获预期的异常。

      try
      {
         //code that could cause the error here
      }
      catch(NullReferenceException nullRefExcep)
      {
         //what you want it to do if the null reference exception occurs
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多