asp.net-mvc – ASP.NET MVC – 在哪里抛出异常?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC – 在哪里抛出异常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
抛出异常的最佳做法,如果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异常.

原文链接:https://www.f2er.com/aspnet/250812.html

猜你在找的asp.Net相关文章