andrew_m
andrew_m

Reputation: 171

Custom exception using NHibernate ISqlExceptionConverter

I need to register custom exception for NHibernate dialect. I have implemented and registered ISqlExceptionConverter, as shown in NHibernate tests. But when exception in code throws, it is not converted. My conversion code even does not call.

My code is really simple:

try
{
        using (ISession sess = OpenSession())
        using (ITransaction tx = sess.BeginTransaction())
        {
           ....
           sess.Save(obj); // invalid object scheduled for inserting
           .....
           tx.Commit(); // exception raises here
        }
}

catch (UniquenessViolationException ex)
{
 // never came here, since exception was not converted and is of type
HibernateException

}

My ISqlExceptionConverter implementation:

public class SqlExceptionConverter : ISQLExceptionConverter
{
        public Exception Convert(AdoExceptionContextInfo exInfo)
        {
                var sqlEx = ADOExceptionHelper.ExtractDbException
(exInfo.SqlException) as SqlException;
                if (sqlEx != null)
                {
                        if (sqlEx.Number == 2627)
                                return new UniquenessViolationException(exInfo.Message, sqlEx,
exInfo.Sql);
                }
                return SQLStateConverter.HandledNonSpecificException
(exInfo.SqlException, exInfo.Message, exInfo.Sql);
        } 

Maybe i missed something?

Upvotes: 3

Views: 2228

Answers (2)

Colin Bowern
Colin Bowern

Reputation: 2192

Appears to be a known issue in NH 2.1.2 GA, fixed in 3.0.0. The patch was applied in r4932. That being said it appears that it isn't called when batching is enabled for the Oracle client so I would still consider the converter broken when batching enabled.

Upvotes: 0

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

You need to register the exception converter.

In code:

configuration.SetProperty(
  Environment.SqlExceptionConverter,
  typeof(SqlExceptionConverter).AssemblyQualifiedName);

In the config file:

<property name="sql_exception_converter">
      Name.Space.SqlExceptionConverter, MyAssembly
</property>

I didn't try this until now, just looked in up in the code. Hope it works, I'll need it too :-)

Upvotes: 3

Related Questions