1

How should NHibernate exceptions be handled during sessions ? There are many examples over the internet:

http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-exceptions https://svn.code.sf.net/p/nhibernate/code/trunk/nhibernate/src/NHibernate/ISession.cs

And many, many StackOwerflow threads that suggest an approach similar to this:

using (ISession session = factory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
    {
        try
        {
            // do some work
            ...
            tx.Commit();
        }
        catch (Exception e)
        {
            if (tx != null) tx.Rollback();
                throw;
        }
    }

But what if an error happens and an exception is thrown ON the 1st line of code(When you're opening a session) ? None of the examples cover it up!

A colege of mine sugested this approach:

ITransaction transaction = null;
    try
    {
        using (ISession session = databaseFacade.OpenSession())
        {
            transaction = session.BeginTransaction();
            //do some work
            ...

            transaction.Commit();
        }
    }
    catch (Exception ex)
    {
        if (transaction != null)
            transaction.Rollback();

        throw new Exception(ex.Message);
    }

1 Answer 1

1

I suggest decoupling components that

  • open session
  • perform db operations

with this approach you can keep logic for handling OpenSession() exceptions inside your 1st line and don't worry later. Reason is that if (as in your case) databaseFacade.OpenSession() throws exception you don't have to catch it and check for transaction since it must be null

    //if OpenSession() throws it's fine , not transaction at all
    using (ISession session = databaseFacade.OpenSession())
    {
        using (ITransaction tx = session.BeginTransaction())
        {
          try
          {
              // do some work
              ...
              tx.Commit();
          }
          catch (Exception e)
          {
            //tx is not null at this point
            tx.Rollback();
            throw;
          }
        }
    }
2
  • it is correct that if OpenSession() throws an exception the transaction does not happen, but how do you handle that exception ? In your code example the try catch block would not handle it. Or am I missing something ?
    – Stralos
    Feb 27, 2015 at 7:05
  • @SomeGuy if OpenSession fails there is nothing to handle as nothing has been created yet. Actually the only thing you should do is to rethrow exception because most likely application will not be able to work
    – tchrikch
    Feb 27, 2015 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.