Using throw in C#

I am building an ASP.NET MVC application, and I am trying to find a way where I can collect  custom error messages if any and send  them back to the view.We have a employee class with id, firstname,lastname and designation properties  and  have a crew manager class with list of employees (IEnumarable) and other properties in it.I have following code that loops through each employee in crewmanager class and  calls ValidateMethod1 and throws custom error message to UI for any particlular employee .This code is working fine without any issue .But now I want to collect error messages for all the employees in crewmanager class and then send to UI. For example Suppose if  I have 10 employess in crewmanager  and below condition is satisfied for 7 employees it should send all the  7 employee's error messages (List) to UI. How can I  acheive this with below code?

foreach (var emp in CrewManager.Employees)
{
    ValidateMethod1(emp.id);
}

 Void ValidateMethod1(emp.id)
  {
        if(condition)
        {
            throw new CustomException("Exception with parameter employee '{0}', emp.id)
        }
 }

Open in new window

ksd123Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fareed Ali KhanCommented:
1) On controller level you can do by overriding the OnException method:

protected override void OnException(ExceptionContext filterContext)
{
    Exception e = filterContext.Exception;
    //Log Exception e
    filterContext.ExceptionHandled=true;
    filterContext.Result = new ViewResult()
    {
        ViewName = "Error"
    };
}

and forward it to Error view if you have any or log into some logging mechanism like eventlog or etc.

2) Global level exception handling. To achieve this you can use the following link:

http://www.codeproject.com/Articles/731913/Exception-Handling-in-MVC
0
käµfm³d 👽Commented:
You should not be using exceptions for control flow. Exceptions are expensive, and they represent "exceptional" situations, not expected/anticipated issues like parameters missing. In my opinion, you should refactor your logic to use proper error handling.

I typically have my service layer do all of the validation of parameters. If anything is in error, then the response object from the service layer will show this via its Errors collection. Then it's simply a matter of looping over that collection and adding it to your model. For example:

View Model
public class HomeViewModel
{
    public string FirstParameter { get; set; }
    public string SecondParameter { get; set; }
    public IEnumerable<string> Errors { get; set; }
}

Open in new window


Controller
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HomeViewModel viewModel)
    {
        ServiceLayer service = new ServiceLayer();
        SomeMethodRequestEntity request = ModelToEntity.Map(viewModel);
        SomeMethodResponseEntity response = service.SomeMethod(request);
        HomeViewModel newViewModel = EntityToModel.Map(response);

        return View(newViewModel);
    }
}

Open in new window


Service Layer
public class ServiceLayer
{
    public SomeMethodResponseEntity SomeMethod(SomeMethodRequestEntity request)
    {
        SomeMethodResponseEntity response = new SomeMethodResponseEntity();

        if (!request.IsValid())
        {
            response.Errors = request.Errors;

            return response;
        }

        //  Other logic

        return response;
    }
}

Open in new window


Service Layer Input
public class SomeMethodRequestEntity
{
    private List<string> errors;

    public string FirstParameter { get; set; }
    public string SecondParameter { get; set; }

    public IEnumerable<string> Errors { get { return this.errors; } }

    public bool IsValid()
    {
        this.errors = new List<string>();

        ValidateFirstParameter();
        ValidateSecondParameter();

        return !this.Errors.Any();
    }

    private void ValidateFirstParameter()
    {
        int temp;

        if (string.IsNullOrWhiteSpace(this.FirstParameter))
        {
            this.errors.Add("FirstParameter is missing.");
        }
        else if (!int.TryParse(this.FirstParameter, out temp))
        {
            this.errors.Add("FirstParameter is invalid.");
        }
    }

    private void ValidateSecondParameter()
    {
        if (string.IsNullOrWhiteSpace(this.FirstParameter))
        {
            this.errors.Add("FirstParameter is missing.");
        }
        else if (!Regex.IsMatch(this.FirstParameter, "^[A-Z]123456789$"))
        {
            this.errors.Add("FirstParameter is invalid.");
        }
    }
}

Open in new window


Service Layer Output
public class SomeMethodResponseEntity
{
    public IEnumerable<string> Errors { get; internal set; }
}

Open in new window


Mappers
public class ModelToEntity
{

    internal static SomeMethodRequestEntity Map(HomeViewModel model)
    {
        SomeMethodRequestEntity entity = new SomeMethodRequestEntity();

        if (model != null)
        {
            entity.FirstParameter = model.FirstParameter;
            entity.SecondParameter = model.SecondParameter;
        }

        return entity;
    }
}

public class EntityToModel
{
    internal static HomeViewModel Map(SomeMethodResponseEntity entity)
    {
        HomeViewModel model = new HomeViewModel();

        if (entity != null)
        {
            model.Errors = entity.Errors;
        }

        return model;
    }
}

Open in new window


As you can see in the controller, the logic is simple(r). It's fairly straight-forward to see what is going on:  You take in the input, map it to a class that the service layer expects, pass the mapped object into the service layer and let the layer do its thing, and then map the response from the service layer into a view model that your display in the view. Your controller is lean and easy to understand. Now all of your validation is in the service layer.

The service layer handles its validation by deferring to the input object's IsValid method. Since we declare the Errors property on both the input and output classes, and since they are of the same type, we can simply forward the errors that the input object determined while executing IsValid onto the output object. That's simple and clean logic, as well as a separation of concerns. Furthermore, should IsValid return true--meaning that no errors were added to the input object's Errors collection--then we can assume that the inputs are good, and we can do the operation(s) that the service layer method is supposed to handle (exemplified by the "Other logic" comment). You can populate the other properties of the output object within the code that you would place in that area of the service layer method. You could easily adapt this logic to suit the requirement you describe above.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ksd123Author Commented:
Thank you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.