2

在我的 ASP.NET MVC 3 应用程序中,我使用 EF 4.2。在我的数据库中,我有一个列的唯一约束。

我尝试插入相同的数据以查看得到的结果,但出现以下错误:

更新条目时出错。有关详细信息,请参阅内部异常。

在内部异常中,我可以看到有关唯一约束的完整错误。但是我怎样才能唯一地捕捉到这个异常来告诉用户这个:

您再次输入相同的值。

这是我目前所做的:

try
{
    UpdateModel<ConditionType>(conditionType, null, null, new string[] { "ConditionTypeId" });
    _conditionTypeRepository.Save();

    return RedirectToAction("conditiontype");
}
catch (Exception ex)
{
    ModelState.AddModelError("", "There was an error while updating: " + ex.Message);
}

但这是一种通用方法。我想做的是提供一个特定的信息。

有什么想法吗?

编辑:

我厌倦了下面的但这次它没有抓住它:

catch (SqlException ex)
{
    if (ex.Number == 2627)
    {
        ModelState.AddModelError("", "You are entering the same value again.");
    }

    ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
}

我挖了一点,结果发现它抛出了一个System.Data.Entity.Infrastructure.DbUpdateException不包含异常号的异常类型。

编辑:

这是我如何解决问题的方法,但我确信这不是解决问题的最佳方法。知道如何重构这段代码吗?

catch (Exception ex) {

    if (ex.InnerException.InnerException.GetType() == typeof(SqlException)) {

        if (((SqlException)ex.InnerException.InnerException).Number == 2627)
            ModelState.AddModelError("", "You are entering the same value again.");
        else
            ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);

    } else {
        ModelState.AddModelError("", "There was an error while updating the value: " + ex.Message);
    }
}
4

3 回答 3

3

您可以执行类似的操作来查找内部异常,即 SqlException,然后以不同方式处理 sql 异常。

catch(Exception ex)
{
    Exception current = ex;
    SqlException se = null;
    do
    {
        se = current.InnerException as SqlException;
        current = current.InnerException;
    }
    while (current != null && se == null);

    if (se != null)
    {
        // Do your SqlException processing here
    }
    else
    {
        // Do other exception processing here
    }
}
于 2011-12-27T14:18:59.700 回答
1

也可以使用 GetBaseException() 方法,因为这会得到根本原因异常,即 SqlException。

于 2017-08-31T09:56:52.700 回答
0

要获得最里面的异常,您可以执行以下操作:

SqlException se = null;
Exception next = ex;

while (next.InnerException != null) 
{
   se = next.InnerException as SqlException;
   next = next.InnerException;
}

if (se != null)
{
    // Do your SqlException processing here
}
else
{
    // Do other exception processing here
}
于 2013-08-01T09:24:01.050 回答