2010-09-12 45 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並處理該異常。