I have seen many times in MVC the following code,when doing a post and saving data :
try
{
//code to save to database
}
catch
{
ModelState.AddRuleViolations(TheModel.GetRuleViolations());
}
Why is not good ?
I will do a simple example : if some error occurs on the database level ( such as simple unique index on a name column ) or even some error occurs whenestablishing the database connection – you will never see what’s happening. And you will have no chance to repair the problem
A slighty better code is :
try
{
ModelState.AddRuleViolations(TheModel.GetRuleViolations());
if(ModelState.Count == 0)// no error in the model
{
//code to save to database
}
}
catch(Exception ex)
{
ModelState.AddModelError("",ex.Message);
}
Please see also how to do logging to the exception at
http://msprogrammer.serviciipeweb.ro/2010/04/19/logging-and-instrumentation/
Leave a Reply