title: Handling NHibernate Exceptions
body: <p>What's the best practice for handling exceptions in NHibernate?</p>
  
  <p>I've got a SubjectRepository with the following:</p>
  
  <pre><code>    public void Add(Subject subject)
      {
          using (ISession session = HibernateUtil.CurrentSession)
          using (ITransaction transaction = session.BeginTransaction())
          {
  
              session.Save(subject);
              transaction.Commit();
          }
      }
  </code></pre>
  
  <p>And a Unit Test as follows:</p>
  
  <pre><code>        [Test]
      public void TestSaveDuplicate()
      {
          var subject = new Subject
          {
              Code = "En",
              Name = "English"
          };
  
          _subjectRepository.Add(subject);
  
          var duplicateSubject = new Subject
          {
              Code = "En",
              Name = "English1"
          };
  
          _subjectRepository.Add(duplicateSubject);
      }
  </code></pre>
  
  <p>I got to the point of handling the error generated by the unit test and got a bit stuck. This fails as expected, though with a GenericADOException, I was expecting a ConstraintViolationException or something similar (there is a uniqueness constraint on the subject code at database level). </p>
  
  <p>The ADOException wraps a MySQL Exception that has a sensible error message but I don't want to start breaking encapsulation by just throwing the inner exception. Particularly as   MySQL isn't finalised as the back end for this project.</p>
  
  <p>Ideally I'd like to be able to catch the exception and return a sensible error to the user at this point. Are there any documented best practice approaches to handling NHibernate Exceptions and reporting back up to the user what went wrong and why?</p>
  
  <p>Thanks,</p>
  
  <p>Matt</p>