加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读