【问题标题】:ASP.NET MVC - Where to throw the exceptions?ASP.NET MVC - 在哪里抛出异常?
【发布时间】:2010-09-12 13:17:28
【问题描述】:

如果在 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;
}

【问题讨论】:

    标签: asp.net-mvc exception


    【解决方案1】:

    永远不要从存储库中抛出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 异常。

    【讨论】:

    • 但是我必须创建自定义异常:(?
    • 是的。这就是你应该做的。
    • 然后我将创建一个名为“NotFoundException”的自定义异常。谢谢你的回答:)
    • 如何创建这个自定义异常?
    【解决方案2】:

    不要在存储库中抛出 HttpException,因为您可能希望将来在非 Http 环境中重用该代码。如果您需要至少一项并在 Controller 中处理该异常,则抛出您自己的 ItemNotFound 异常,或者返回 null 并处理该异常。

    【讨论】:

      【解决方案3】:

      我会将HttpException 扔到控制器中,然后从存储库中返回null

      【讨论】:

      • 从存储库中返回 null .. 这很有意义 - 请您再深入一点吗?
      猜你喜欢
      • 2016-03-10
      • 2013-02-08
      • 1970-01-01
      • 2011-04-24
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多