2011-03-22 55 views
1

我需要看到由SqlException产生的错误代码 - 但是,我无法启动一个。我使用NHibernate,并在我的桌子上安装了SQL UNIQUE CONSTRAINT。当违反这个约束条件时,我需要捕获错误代码并基于此创建一个用户友好的消息。这里是我的try/catch的示例:在尝试NHibernate事务时捕获SqlException

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); 
    } 
} 

请原谅我的无知。

回答

7

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 
    } 
    ... 
} 
+1

你达人!非常感谢。我喜欢这个网站。 – BueKoW 2011-03-22 14:58:08

+0

@BueKoW,不要忘记将答案标记为已接受。 – 2011-03-22 15:22:38

2

直接在控制器捉住SQLEXCEPTION的相反,我会成立了一个SQLExceptionConverter翻译成更有意义例外。