Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Where to throw the exceptions?

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;
}
like image 529
ebb Avatar asked Sep 12 '10 13:09

ebb


People also ask

How is exception handling done in MVC?

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.

Which of the following code shows how exceptions are handled in MVC?

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.

Can we use try catch in MVC?

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.


1 Answers

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.

like image 113
blockhead Avatar answered Oct 19 '22 22:10

blockhead