Thực hành tốt nhất để ném ngoại lệ nếu không có mục nhập nào được tìm thấy trong db?ASP.NET MVC - Trường hợp ném ngoại lệ?
// 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);
}
hoặc
// 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;
}
Nhưng sau đó tôi phải tạo ngoại lệ tùy chỉnh: (? – ebb
Có bạn làm. Và đó là những gì bạn nên * làm. – blockhead
Tôi sẽ chỉ tạo một ngoại lệ tùy chỉnh Sau đó, hãy đặt tên là "NotFoundException". Cảm ơn bạn đã trả lời :) – ebb