如果在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