I have a website which is utilzing MVC3. I have an n-tier architecture and I am curious at what level it is best to catch errors.
For isntance let’s say I have a Students table I have a StudentRepository with a function such as:
StudentRepository.GetHightestGrade(studentId)
So should I have my Repositry function have a try/catch block – or should I put the try/catch directly into the ActionResult function. OR would I be better served adding in a business class and then my ActionResult function would do something such as
Business.GetHighestGrade(studentId) and that function simply has a try/catch and calls the Repository function?
You should really only wrap methods in try/catch if you are trying to prevent errors from bubbling up the stack. Generally it’s best to put the try/catch at the top layers, to shield the users from the errors. Lower layers should generally throw exceptions during exceptional circumstances, you should only try to catch them in higher layers.
You will find your code is much more readable without a ton of try/catch blocks, I personally try to avoid them when I can, and let the MVC3 HandleError filter attribute take care of displaying error messages. However sometimes you may want to retry an operation if it throws an exception, which makes a good try/catch candidate.
Take a look at ELMAH — using it should help you write code that avoids exceptions in the first place. But you should only explicitly try/catch if you are expecting an exception, and want to take some action in response to it.