Asp.net-Mvc

ASP.NET MVC - 在哪裡拋出異常?

  • September 12, 2010

如果在數據庫中找不到條目,則拋出異常的最佳實踐?

// 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;
}

永遠不要從儲存庫中拋出HttpException…這是錯誤的抽象級別。如果您不希望您的儲存庫返回null,請執行以下操作:

// CONTROLLER
public ActionResult Edit(int categoryId, int id)
{
   try {
      Product target = Products.GetById(id);
   }
   catch(ProductRepositoryException e) {
      throw new HttpException(404, "Product not found")
   }

   return View("Edit", target);
}

// REPOSITORY
public Product GetById(int id)
{
   Product target = context.Products.FirstOrDefault(x => x.productId == id);
   if (target == null) throw new ProductRepositoryException();

   return target;
}

您的儲存庫不應該知道任何關於 HTTP 的資訊,但您的控制器可以知道儲存庫。因此,您從儲存庫中拋出一個儲存庫異常,並將其“翻譯”為控制器中的 HTTP 異常。

引用自:https://stackoverflow.com/questions/3694977