ASP.NET MVC - 在哪里抛出异常?

ebb*_*ebb 17 asp.net-mvc exception

如果在数据库中找不到条目,​​则抛出异常的最佳做法是什么?

// 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);
}
Run Code Online (Sandbox Code Playgroud)

要么

// 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;
}
Run Code Online (Sandbox Code Playgroud)

blo*_*ead 26

永远不要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;
}
Run Code Online (Sandbox Code Playgroud)

您的存储库不应该知道有关HTTP的任何信息,但您的控制器可以了解存储库.因此,您从存储库中抛出一个存储库异常,并将其"转换"为控制器中的HTTP异常.

  • 是的你是.这就是你应该*做的事情. (7认同)