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;
}
The HandleErrorAttribute is an attribute that can be used to handle exceptions thrown by an action method or a controller. You can use it to display a custom view on a specific exception occurred in an action method or in an entire controller.
HandleError Attribute This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.
We have try catch block for error handling, But in case of MVC we have exception filters. In such case we can handle errors at filter level. i.e. by using exception filters.
Never throw an HttpException
from a repository...it's the wrong level of abstraction. If you don't want your repository to return null
, do something like this:
// 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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With