抛出异常的最佳做法,如果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异常.