1

I have a ASP.NET project and in some part of it I call a business rule to test the form:

[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");
        }
    }

On the BLL, I have this:

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

However, the console only prints that the exception has been thrown, but not the message that I asked for. Is there any syntax mistake or something that I just messed up?

  • I bet Exception is thrown before the `else {}`, because `Value` is null. Use `try {} catch {}` – Lab Lab Sep 24 '18 at 14:46
  • Don't use exceptions to handle expected program flow. Exceptions should be for truly exceptional problems. Failed validation should not result in an exception. – mason Sep 24 '18 at 15:41

1 Answers1

0

You can do something like this,

Create Result Object which can be used to transmit data between layers.

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

Transfer as a Result Object to the calling layer (here in your case Controller) after all your business validations.

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

In Controller

[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);
}
Hary
  • 5,690
  • 7
  • 42
  • 79