Best practice to throw the exception if no entry found in the db?
// 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);
}
or
// 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;
}
Never throw an
HttpExceptionfrom a repository…it’s the wrong level of abstraction. If you don’t want your repository to returnnull, do something like this:Your repository should not know anything about HTTP, but your controller can know about the repository. So you throw a repository exception from the repository, and “translate” that into an HTTP Exception in the controller.