2011-03-22 54 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翻譯成更有意義例外。