ISqlExceptionConverter

ISqlExceptionConverter

本文介绍了使用NHibernate ISqlExceptionConverter的自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为NHibernate方言注册自定义例外.我已经实现了已注册的ISqlExceptionConverter,如NHibernate测试所示.但当代码中的异常引发时,不会进行转换.我的转换码甚至不打电话.

I need to register custom exception for NHibernate dialect. I have implemented andregistered ISqlExceptionConverter, as shown in NHibernate tests. Butwhen exception in code throws, it is not converted. My conversion codeeven does not call.

我的代码非常简单:

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

}

我的ISqlExceptionConverter实现:

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);
        } 

也许我错过了什么?

推荐答案

您需要注册异常转换器.

You need to register the exception converter.

在代码中:

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

在配置文件中:

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

这篇关于使用NHibernate ISqlExceptionConverter的自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 10:57