2010-09-12 12 views
16

Le migliori pratiche per lanciare l'eccezione se nessuna voce trovata nel db?ASP.NET MVC: dove vengono generate le eccezioni?

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

o

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

risposta

19

Non gettare mai uno HttpException da un repository ... è il livello di astrazione sbagliato. Se non si desidera che il repository per tornare null, fare qualcosa di simile:

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

Il repository non dovrebbe sapere nulla di HTTP, ma il controller può conoscere il repository. Quindi si lancia un'eccezione di repository dal repository e si "traduce" in un'eccezione HTTP nel controller.

+0

Ma poi devo creare eccezioni personalizzate :(? – ebb

+6

Sì. E questo è quello che dovresti * fare. – blockhead

+0

Creerò solo un'eccezione personalizzata chiamato "NotFoundException" quindi. Grazie per la risposta :) – ebb

0

vorrei buttare HttpException nel controller, e restituire null dal repository.

+1

Restituisce null dal repository .. che dosent ha senso - potresti approfondire un po 'per favore? – ebb

+0

Intendevo '... OrDefault();' ... – Nate

3

Non lanciare una HttpException nel repository, poiché si potrebbe desiderare di riutilizzare quel codice in futuro in un ambiente non Http. Getta la tua eccezione ItemNotFound se richiedi almeno un elemento e gestisci tale eccezione nel Controller, oppure restituisci null e gestiscilo.

Problemi correlati