views:

304

answers:

2

Hi everybody.

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?

A: 

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 :-)

Stefan Steinegger
Thanks, i have registered converter. I also debug NHibernate code. There are alot of places where conversion performs, but it does not perform during flushing the session... Not sure, is this by design, or i missed something.
andrew_m
What exception is thrown by NH which you expect to be converted?
Stefan Steinegger
NHibernate throws HibernateException. I have also set breakpoint to my converter class and debugger does not hit it, however i checked at runtime - my converter was properly registered at configuration object.
andrew_m
Whats the reason for the NHibernate Exception? I'm pretty sure that the converter does not convert NHibernate exceptions (probably unless they are created by a default Converter, if there would be such cases). You can only convert exceptions specific to the database layer. It's an **Sql** Exception Converter, isn't it?
Stefan Steinegger
A: 

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.

Colin Bowern