What is the best practice for handling exceptions in NHibernate?
I have a SubjectRepository with the following:
public void Add(Subject subject) { using (ISession session = HibernateUtil.CurrentSession) using (ITransaction transaction = session.BeginTransaction()) { session.Save(subject); transaction.Commit(); } }
And Unit Test as follows:
[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); }
I got to handling the error created by Unit Test and got a little stuck. This does not happen as expected, although with the exception of a GenericADOException, I was expecting a ConstraintViolationException or something similar (there is a uniqueness constraint for the theme code at the database level).
An ADOException wraps a MySQL exception that has a reasonable error message, but I don't want to start breaking encapsulation just by throwing an internal exception. In particular, since MySQL is not completed as the back of this project.
Ideally, I would like to catch an exception and return a reasonable error to the user. Are there any documented approaches to handling NHibernate exceptions and reporting to the user, what went wrong and why?
Thanks,
Matt
exception exception-handling nhibernate unique-constraint
Matt sharpe
source share