asp.net-mvc – ASP.NET MVC – 在哪里抛出异常?
发布时间:2020-05-24 00:36:18 所属栏目:asp.Net 来源:互联网
导读:抛出异常的最佳做法,如果db中没有找到条目? // CONTROLLERpublic ActionResult Edit(int categoryId, int id){ Product target = Products.GetById(id); if (target == null) throw new HttpException(404, Product not fou
|
抛出异常的最佳做法,如果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);
}
要么 // 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;
}
解决方法不要从存储库中引发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;
}
您的存储库不应该知道有关HTTP的任何信息,但您的控制器可以了解存储库.所以您从存储库中抛出存储库异常,并将其转换为控制器中的HTTP异常. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc-4 – WebApi Json.NET自定义日期处理
- asp.net-web-api – AttributeRouting不能与HttpConfigurat
- 如何在asp.net webform中使用异步/等待实现异步页面?
- asp.net-mvc – ServiceStack应该是MVC应用程序中的服务层还
- dropdownlist事件不显示在属性窗口asp.net Visual Studio 2
- 学习Asp.Net WebForms或Asp.Net MVC
- asp.net – 我可以愚弄HttpRequest.Current.Request.IsLoca
- asp.net简单生成XML文件的方法
- asp.net-core – 从与xproj相同的解决方案引用csproj
- asp.net – 如何使用SqlDependency使OutputCache依赖于每个
推荐文章
站长推荐
热点阅读
