asp.net-mvc ASP.NET MVC - 在哪里抛出异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3694977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - Where to throw the exceptions?
提问by ebb
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;
}
回答by blockhead
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:
永远不要HttpException
从存储库中抛出......这是错误的抽象级别。如果您不希望您的存储库返回null
,请执行以下操作:
// 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.
您的存储库不应该了解 HTTP,但您的控制器可以了解存储库。因此,您从存储库中抛出存储库异常,并将其“转换”为控制器中的 HTTP 异常。
回答by Moo
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.
不要在存储库中抛出 HttpException,因为您可能希望将来在非 Http 环境中重用该代码。如果您需要至少一个项目并在控制器中处理该异常,则抛出您自己的 ItemNotFound 异常,或者返回 null 并处理该异常。
回答by Nate
I would throw HttpException
in the controller, and return null
from the repository.
我会投入HttpException
控制器,然后null
从存储库返回。