Implement CustomException

4

I have a messaging class, in which valid if any required field is empty or business rules which information by a string variable comes to the presentation.

public class Mensajeria
{
    Resto de código
}

My question is implementing CustomException, I can do the same and if the answer is if the message would arrive until the presentation layer having to go through the ApplicationApp layer.

    
asked by Pedro Ávila 13.04.2016 в 19:42
source

1 answer

5

If you are going to apply business rule validations, use a framework that helps you as you are

FluentValidation

Then you could apply validation rules indicating which fields you can be vacations.

When executing the validations you will get the list of errors. Do not invent the wheel there are already libraries that allow validations to be applied in business entities.

You define the validation rules

public class CustomerValidator : AbstractValidator<Customer> {
   public CustomerValidator() {
     RuleFor(customer => customer.Surname).NotNull();
   }
}

you execute the validations

Customer customer = new Customer(); //esta entidad vendria desde la presentacion
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

and finally you take the error messages if there is any

if(! results.IsValid) {
   foreach(var failure in results.Errors) {
     Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
   }
 }

Then you can return the list of messages or you could return an Exception containing the string of these messages. I would recommend that you return an exceltion, it is more this framework supports it if you use

 validator.ValidateAndThrow(customer);

from the UI you simply capture the exception with a try..catch

    
answered by 13.04.2016 / 20:05
source