【发布时间】:2012-07-02 19:02:49
【问题描述】:
我正在开发一个 asp.net mvc 应用程序,其中 user1 可以删除 user2 之前刚刚加载的数据记录。 User2 要么更改这个不存在的数据记录(更新),要么在另一个违反外键约束的表中使用此数据进行插入。
你在哪里捕捉到这样的预期异常?
在您的 asp.net mvc 应用程序的 Controller 中还是在业务服务中?
只是一个旁注:我只在这里捕获 SqlException,如果它是一个 ForeignKey 约束异常,告诉用户另一个用户已经删除了某个父记录,因此他不能创建测试计划。但是这段代码还没有完全实现!
控制器:
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);
}
或
商业服务:
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;
}
然后在控制器中:
public JsonResult CreateTestplan(Testplan testplan)
{
Result result = testplanService.CreateTestplan(testplan);
return Json(new { success = result.success, error = result.error }, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
标签: asp.net-mvc exception-handling