asp.net-mvc – ASP.NET MVC – 在哪里抛出异常?
发布时间:2020-12-15 23:44:55 所属栏目:asp.Net 来源:网络整理
导读:抛出异常的最佳做法,如果db中没有找到条目? // CONTROLLERpublic 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)
抛出异常的最佳做法,如果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 – 通过不同的Web应用程序共享相同的dll
- ASP.Net Web应用程序安全性不适用于IIS 7?
- iis-7 – ASP页面中的错误“80131509”
- asp.net-mvc-3 – 如何使用MVC中的存储库模式创建
- asp.net-mvc-3 – URL.Action在构造URL时包含id
- asp.net – 来自ASHX处理程序的Sever.Transfer,H
- asp.net – MVC3 – 向控制器添加一个文件夹?
- asp.net – Web用户控件通过XML填充项目
- asp.net-mvc – 经典ASP和MVC并排,不同的项目?
- asp.net-mvc – Telerik MVC Chart ClientEvents
热点阅读