【问题标题】:Catch SqlException when Attempting NHibernate Transaction尝试 NHibernate 事务时捕获 SqlException
【发布时间】:2011-03-22 14:46:27
【问题描述】:

我需要查看由SqlException 生成的错误代码 - 但是,我无法触发。我使用 NHibernate 并在我的桌子上有一个 SQL UNIQUE CONSTRAINT 设置。当违反该约束时,我需要捕获错误代码并据此生成用户友好的消息。这是我的 try/catch 示例:

using (var txn = NHibernateSession.Current.BeginTransaction()) {
    try {
        Session["Report"] = report;
        _reportRepository.SaveOrUpdate(report);
        txn.Commit();
        Fetch(null, report.ReportId, string.Empty);
    } catch (SqlException sqlE) {
        var test = sqlE.ErrorCode;
        ModelState.AddModelError("name", Constants.ErrorMessages.InvalidReportName);
        return Fetch(report, report.ReportId, true.ToString());
    } catch (InvalidStateException ex) {
        txn.Rollback();
        ModelState.AddModelErrorsFrom(ex, "report.");
    } catch (Exception e) {
        txn.Rollback();
        ModelState.AddModelError(String.Empty, Constants.ErrorMessages.GeneralSaving);
    }
}

请原谅我的无知。

【问题讨论】:

    标签: c# asp.net asp.net-mvc nhibernate exception


    【解决方案1】:

    Check this out 说明了如何捕获 GenericADOException 并查看 InnerException 属性:

    catch (GenericADOException ex)
    {
        txn.Rollback();
        var sql = ex.InnerException as SqlException;
        if (sql != null && sql.Number == 2601)
        {
            // Here's where to handle the unique constraint violation
        }
        ...
    }
    

    【讨论】:

      【解决方案2】:

      我没有直接在控制器中捕获 SqlException,而是设置了一个 SQLExceptionConverter 来将其转换为更有意义的异常。

      【讨论】:

        猜你喜欢
        • 2016-02-10
        • 1970-01-01
        • 2016-09-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-28
        • 2023-04-07
        • 1970-01-01
        • 2019-08-25
        相关资源
        最近更新 更多