开发者

ASP.NET MVC - Where to throw the exceptions?

开发者 https://www.devze.com 2023-01-15 15:28 出处:网络
Best practice to throw the exception if no entry found in the db? // CONTROLLER public ActionResult Edit(int categoryId, int id)

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.FirstOr开发者_开发技巧Default(x => x.productId == id);
    if (target == null) throw new HttpException(404, "Product not found with given id");

    return target;
}


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.


Do not throw a HttpException in the Repository, as you may want to reuse that code in the future in a non-Http environment. Throw your own ItemNotFound exception if you require at least one item and handle that exception in the Controller, or return null and handle that.


I would throw HttpException in the controller, and return null from the repository.

0

精彩评论

暂无评论...
验证码 换一张
取 消