I am developing an asp.net mvc application where user1 could delete data records which were just loaded before by user2. User2 either changes this non-existent data record (Update) or is doing an insert with this data in another table that a foreign-key constraint is violated.
Where do you catch such expected exceptions?
In the Controller of your asp.net mvc application or in the business service?
Just a sidenote: I only catch the SqlException here if its a ForeignKey constraint exception to tell the user that another user has deleted a certain parent record and therefore he can not create the testplan. But this code is not fully implemented yet!
Controller:
public JsonResult CreateTestplan(Testplan testplan)
{
bool success = false;
string error = string.Empty;
try
{
success = testplanService.CreateTestplan(testplan);
}
catch (SqlException ex)
{
error = ex.Message;
}
return Json(new { success = success, error = error }, JsonRequestBehavior.AllowGet);
}
OR
Business service:
public Result CreateTestplan(Testplan testplan)
{
Result result = new Result();
try
{
using (var con = new SqlConnection(_connectionString))
using (var trans = new TransactionScope())
{
con.Open();
_testplanDataProvider.AddTestplan(testplan);
_testplanDataProvider.CreateTeststepsForTestplan(testplan.Id, testplan.TemplateId);
trans.Complete();
result.Success = true;
}
}
catch (SqlException e)
{
result.Error = e.Message;
}
return result;
}
then in the Controller:
public JsonResult CreateTestplan(Testplan testplan)
{
Result result = testplanService.CreateTestplan(testplan);
return Json(new { success = result.success, error = result.error }, JsonRequestBehavior.AllowGet);
}
Foreign key constraint violation should be checked and displayed properly. You can easily check if rows in related table exist and show proper message. The same can be done with row updates. Servers return number of rows affected, so you know what happens.
Even if you don’t make these checks, you should catch SQL exceptions. For average application user, message about constraint violation means nothing. This message is for developer and you should log it with ELMAH or Log4Net library. User should see message similar to “We are sorry. This row has been probably modified by another user and your operation has become invalid.” and in case he asks developer about it, developer should check logs and see the cause.
EDIT
I believe you should check errors in service. Controller should not be aware of data access layer. For controller, it doesn’t matter if you store data in SQL database or in files. Files can throw file access exception, SQL has other ones. Controller shouldn’t worry about it. You can catch data access layer exceptions in service and throw exception with type dedicated for service layer. Controller can catch it and display proper message. So the answer is: