【问题标题】:C# console doesn't print exception messageC# 控制台不打印异常消息
【发布时间】:2018-09-24 14:39:47
【问题描述】:

我有一个 ASP.NET 项目,在其中的某些部分我调用了一个业务规则来测试表单:

[HttpPost]
    public ActionResult InsertProduct(Product Product)
    {
        try
        {
            InsertProductBLL ProductInsertion = new InsertProductBLL (Product.Value, Product.Description);
            ProductInsertion.IsValid();
            return PartialView("Success");
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
            return PartialView("Fail");
        }
    }

在 BLL 上,我有这个:

public void IsValid()
{
    if (Value> 10) ; //I just want the else section
    else
    {
            Exception e = new Exception("Insert a bigger value");
            throw e;
    }
}

但是,控制台只打印出异常已被抛出,而不是我要求的消息。是否有任何语法错误或我刚刚搞砸的东西?

【问题讨论】:

  • 我打赌在else {} 之前抛出异常,因为Value 为空。使用try {} catch {}
  • 不要使用异常来处理预期的程序流。例外应该是针对真正例外的问题。验证失败不应导致异常。

标签: asp.net asp.net-mvc exception razor console


【解决方案1】:

你可以这样做,

创建Result对象,可用于在层之间传输数据。

public class Result
{
   public HasResult { get; set; }
   public ErrorMessage { get; set;}
   public SuccessMessage { get; set;}
}

在所有业务验证之后,作为Result 对象传输到调用层(在您的情况下为Controller)。

public Result IsValid(int Value)
{
    var result = new Result();

    result.HasResult = Value > 10;//set this after all your business rules 

    if(HasResult)
    {
        result.SuccessMessage = "Success"; 
    }    
    else
   {
         result.ErrorMessage = "Insert a bigger value";
   }

    return result;
}

在控制器中

[HttpPost]
public ActionResult InsertProduct(Product Product)
{
   var returnMessage = "";

    try
    {
        InsertProductBLL ProductInsertion = new InsertProductBLL (Product.Value, Product.Description);

        var result = ProductInsertion.IsValid(Product.Value);

        returnMessage  = result.HasResult 
        ? result.SuccessMessage
        : result.ErrorMessage;
    }
    catch (Exception e)
    {
        Console.Write(e.Message);
        returnMessage = "Fail";
    }

    return PartialView(returnMessage);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多