2010-09-12 46 views
16

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

回答

19

永远不要从存储库中抛出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异常。

+0

但是我必须创建自定义异常:(? – ebb 2010-09-12 13:33:13

+6

是的,你应该这样做,这就是你*应该*做的 – blockhead 2010-09-12 13:55:25

+0

我只是创建一个自定义异常那么命名为“NotFoundException”。谢谢你的回答:) – ebb 2010-09-12 14:23:13

0

我会在控制器扔HttpException,并从资源库返回null

+1

从存储库返回null ..该剂量是有意义的 - 你可以进一步深入一点吗? – ebb 2010-09-12 13:22:43

+0

我的意思是...... OrDefault();'... – Nate 2010-09-13 14:41:08

3

不要在存储库中抛出HttpException,因为您可能希望将来在非Http环境中重用该代码。如果您至少需要一个项目并在Controller中处理该异常,则抛出您自己的ItemNotFound异常,或返回null并处理该异常。