如果在db中没有找到条目,抛出异常的最佳做法是什么?ASP.NET MVC - 抛出异常的地方在哪里?
// CONTROLLER
public ActionResult Edit(int categoryId, int id)
{
Product target = Products.GetById(id);
if (target == null) throw new HttpException(404, "Product not found");
return View("Edit", target);
}
// REPOSITORY
public Product GetById(int id)
{
return context.Products.FirstOrDefault(x => x.productId == id);
}
或
// CONTROLLER
public ActionResult Edit(int categoryId, int id)
{
return View("Edit", Products.GetById(id));
}
// REPOSITORY
public Product GetById(int id)
{
Product target = context.Products.FirstOrDefault(x => x.productId == id);
if (target == null) throw new HttpException(404, "Product not found with given id");
return target;
}
但是我必须创建自定义异常:(? – ebb 2010-09-12 13:33:13
是的,你应该这样做,这就是你*应该*做的 – blockhead 2010-09-12 13:55:25
我只是创建一个自定义异常那么命名为“NotFoundException”。谢谢你的回答:) – ebb 2010-09-12 14:23:13