In MVC what is the best method to manage exceptions or errors in the business? I found several solutions but do not know which to choose.
Solution 1
public Person GetPersonById(string id)
{
MyProject.Model.Person person = null;
try
{
person = _personDataProvider.GetPersonById(id);
}
catch
{
// I use a try / catch to handle the exception and I return a null value
// I don't like this solution but the idea is to handle excpetion in
// business to always return valid object to my MVC.
person = null;
}
return person;
}
Solution 2
public Person GetPersonById(string id)
{
MyProject.Model.Person person = null;
person = _personDataProvider.GetPersonById(id);
// I do nothing. It to my MVC to handle exceptions
return person;
}
Solution 3
public Person GetPersonById(string id, ref MyProject.Technical.Errors errors)
{
MyProject.Model.Person person = null;
try
{
person = _personDataProvider.GetPersonById(id);
}
catch (Exception ex)
{
// I use a try / catch to handle the exception but I return a
// collection of errors (or status). this solution allow me to return
// several exception in case of form validation.
person = null;
errors.Add(ex);
}
return person;
}
Solution 4
// A better idea ?
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
I would also suggest you to think about Null Object Pattern. Instead of returning null, return an empty object so that you don't have to perform multiple if null checks. You should create an abstract Person class that has a static property like NullPerson which contains default values. If your DAL returns null, you would return NullPerson. You can find more information on Null Object Pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With